使用ggplot更改特定值颜色
Changing specific value color with ggplot
我将 geom_point() 与 ggplot 结合使用,本质上创建了一个 -coefplot- 的等价物,在一个图上具有 5 个不同模型的系数。
我可以只更改一个点(以及相应的 CI 条)的颜色吗? color/font/etc 呢?单个轴刻度标签的?例如,如果我只想为 Model 3 的标签将字体设置为粗体,并将 Model 3 的系数点(+ CI 条)设置为红色(或任何其他颜色来区分它)。我试过 scale_fill_manual
,但似乎没用。
我当前的代码(scale_x_discrete,模型的名称只是模型 1、2、3 等,我将它们按顺序放在那里):
ggplot(d, aes(x = var, y = coef)) +
geom_point() +
geom_pointrange(aes(ymin = cilow, ymax = ciupper)) +
scale_x_discrete(limits = model_order, labels = model_label) +
theme_minimal()
您可以使用条件只为您想要的点和 CI 着色。 ifelse(test to select your group, color name if yes, color name if not)
.
library(tidyverse)
df=iris %>%
group_by(Species) %>%
summarise(min=min(Petal.Length),
max=max(Sepal.Length),
mean=(min+max)/2)
ggplot(df,aes(Species, mean,color=Species)) +
geom_point() +
geom_pointrange(aes(ymin = min, ymax = max))+
scale_color_manual(values = ifelse(df$Species=="setosa","red","black"))
要更改轴标签,您可以使用 ggtext
,如
中所示
library(ggtext)
library(glue)
highlight = function(x, pat, color="black", family="") {
ifelse(grepl(pat, x), glue("<b style='font-family:{family}; color:{color}'>{x}</b>"), x)
}
ggplot(df,aes(Species, mean,color=Species)) +
geom_point() +
geom_pointrange(aes(ymin = min, ymax = max))+
scale_x_discrete(labels=function(x) highlight(x, "setosa", "purple")) +
scale_color_manual(values = ifelse(df$Species=="setosa","red","black"))
theme_bw()+
theme(axis.text.x=element_markdown(size=15))
它不适用于 theme_minimal
,所以我使用了另一个。
我将 geom_point() 与 ggplot 结合使用,本质上创建了一个 -coefplot- 的等价物,在一个图上具有 5 个不同模型的系数。
我可以只更改一个点(以及相应的 CI 条)的颜色吗? color/font/etc 呢?单个轴刻度标签的?例如,如果我只想为 Model 3 的标签将字体设置为粗体,并将 Model 3 的系数点(+ CI 条)设置为红色(或任何其他颜色来区分它)。我试过 scale_fill_manual
,但似乎没用。
我当前的代码(scale_x_discrete,模型的名称只是模型 1、2、3 等,我将它们按顺序放在那里):
ggplot(d, aes(x = var, y = coef)) +
geom_point() +
geom_pointrange(aes(ymin = cilow, ymax = ciupper)) +
scale_x_discrete(limits = model_order, labels = model_label) +
theme_minimal()
您可以使用条件只为您想要的点和 CI 着色。 ifelse(test to select your group, color name if yes, color name if not)
.
library(tidyverse)
df=iris %>%
group_by(Species) %>%
summarise(min=min(Petal.Length),
max=max(Sepal.Length),
mean=(min+max)/2)
ggplot(df,aes(Species, mean,color=Species)) +
geom_point() +
geom_pointrange(aes(ymin = min, ymax = max))+
scale_color_manual(values = ifelse(df$Species=="setosa","red","black"))
要更改轴标签,您可以使用 ggtext
,如
library(ggtext)
library(glue)
highlight = function(x, pat, color="black", family="") {
ifelse(grepl(pat, x), glue("<b style='font-family:{family}; color:{color}'>{x}</b>"), x)
}
ggplot(df,aes(Species, mean,color=Species)) +
geom_point() +
geom_pointrange(aes(ymin = min, ymax = max))+
scale_x_discrete(labels=function(x) highlight(x, "setosa", "purple")) +
scale_color_manual(values = ifelse(df$Species=="setosa","red","black"))
theme_bw()+
theme(axis.text.x=element_markdown(size=15))
它不适用于 theme_minimal
,所以我使用了另一个。