我有如下的情节如下。它是用下面的命令创建的:
library(ggplot2)
df <- data.frame(cond = factor(rep(c("A", "B"), each = 200)),
rating = c(rnorm(200), rnorm(200, mean=.8)))
ggplot(df, aes(x=rating, fill=cond)) +
geom_density(alpha = .3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE")
现在,我想把传说标题从cond修改为NEW legend title。
所以,我只是添加了下面的行添加上述代码的结尾:
+labs(colour="NEW LEGEND TITLE")
但这并不奏效。正确的做法是什么?
我注意到有两种方法来改变/指定图例。ggboxplot()的标题:
library(ggpubr)
bxp.defaultLegend <- ggboxplot(ToothGrowth, x = "dose", y = "len",
color = "dose", palette = "jco")
# Solution 1, setup legend.title directly in ggboxplot()
bxp.legend <- ggboxplot(ToothGrowth, x = "dose", y = "len",
color = "dose", palette = "jco", legend.title="Dose (mg)")
# Solution 2: Change legend title and appearnace in ggboxplot() using labs() and theme() option:
plot1 <- bxp.defaultLegend + labs(color = "Dose (mg)") +
theme(legend.title = element_text(color = "blue", size = 10), legend.text = element_text(color = "red"))
ggarrange(list(bxp.legend, bxp.defaultLegend, plot1), nrow = 1, ncol = 3, common.legend = TRUE)
代码基于GitHub中的示例进行修改。
为了添加到列表中(这里的其他选项对我不起作用),你还可以为ggplot使用update_labels函数:
p <- ggplot(df, aes(x=rating, fill=cond)) +
geom_density(alpha=.3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE")
update_labels(p, list(colour="MY NEW LEGEND TITLE")
这也将允许您更改x轴和y轴标签,使用单独的行:
update_labels(p, list(x="NEW X LABEL",y="NEW Y LABEL")