如何更改 ggplot2 中 "theme" 参数中的图例标签?

How to change legend label in "theme" argument in ggplot2?

我正在使用 ggplot2 ro 绘制误差线图。对于图例,我想要这样:

  1. 里面的情节。我知道函数 theme(legend.position) 可以做到这一点。

  2. 在带有函数表达式的图例标签中使用乳胶符号。

我已经阅读了一些构建图例的参考资料,但仍然没有找到我想要的内容。我可以执行 1 或 2,但在我的情节中不能同时执行。

以下是有问题的情节的R代码。由于我的声望不足以post一张图片,请将代码复制到您的R中以查看情节。我只想保留标签包含 \beta_A 和 \beta_B,但标签不包含第 1 组和第 2 组。

有什么想法吗?谢谢!

library(ggplot2); library(scales) #for alpha
varx <- rep(c("group1", "group2"), each = 3)
vary <- rep(c("A", "B", "C"), 2)
poi <- sample(20:30, 6)
upper <- sample(40:50, 6)
lower <- sample(1:10, 6)

dat <- data.frame(varx, vary, poi, upper, lower)
dat
  #      varx vary poi upper lower
  # 1 group1    A  29    42    10
  # 2 group1    B  21    48     9
  # 3 group1    C  26    47     8
  # 4 group2    A  30    44     4
  # 5 group2    B  27    49     6
  # 6 group2    C  24    43     7

pp <- ggplot(dat, aes(colour = varx, y = poi, x = vary)) 

limits <- aes(ymax = upper, ymin = lower)

pp  + geom_point(aes(shape=varx), position = position_dodge(0.3), size = 2) + 
  ## dodge make the lines not stack upon each other
  geom_errorbar(limits, size = 1, width = 0.15, position = position_dodge(0.3)) + 
  theme_bw() + ## Get rid of the grey background
  geom_hline(yintercept = 0, linetype = "dotdash") +
  coord_cartesian(ylim = c(1, 60)) + 
  scale_shape_manual(values = c(17, 19, 18)) + 
  scale_colour_hue(labels =  c(expression(beta[A]), expression(beta[N]))) + 
  theme(plot.margin = unit(rep(1.5, 4),"mm"),
        legend.justification= c(1, 0), 
        legend.position = c(1, 0.5),
        legend.key = element_blank(),## Get rid of the legend box 
        legend.title = element_blank(),
        legend.text = element_text(size = 10, face = "bold"),
        legend.background = element_rect(fill=alpha(0.0001))) +
  labs(x = NULL, y = NULL)

要删除图例,您只需将 guides(shape=FALSE) 添加到您的绘图中即可。在 guides 中,您可以决定哪种美学应该显示图例。要合并图例,请使标签相同,ggplot 将完成剩下的工作。

## Use this label for both aesthetic legends
labels =  c(expression(beta[A]), expression(beta[N]))

pp  + geom_point(aes(shape=varx), position = position_dodge(0.3), size = 2) + 
  ## dodge make the lines not stack upon each other
  geom_errorbar(limits, size = 1, width = 0.15, position = position_dodge(0.3)) + 
  theme_bw() + ## Get rid of the grey background
  geom_hline(yintercept = 0, linetype = "dotdash") +
  coord_cartesian(ylim = c(1, 60)) + 
  scale_shape_manual(values = c(17, 19, 18), labels=labels) +
  scale_colour_hue(labels = labels) + 
  theme(plot.margin = unit(rep(1.5, 4),"mm"),
        legend.justification= c(1, 0), 
        legend.position = c(1, 0.5),
        legend.key = element_blank(),## Get rid of the legend box 
        legend.title = element_blank(),
        legend.text = element_text(size = 10, face = "bold"),
        legend.background = element_rect(fill=alpha(0.0001))) +
  labs(x = NULL, y = NULL) # + guides(shape=FALSE) # if wanting to remove