【问题标题】:Cannot change ggplot boxplot legend name无法更改 ggplot 箱线图图例名称
【发布时间】:2021-04-07 04:48:57
【问题描述】:

我正在使用此代码:

 library(ggplot2)
 library(reshape)
 mtcars <- melt(mtcars, id="am")
 mtcars$am <- as.character(mtcars$am)
 p <- ggplot(mtcars, aes(x = variable, y = value)) + 
    geom_boxplot(aes(color = am), width = 0.4, size = 0.4, position = position_dodge(0.6), 
        outlier.shape=NA, notch=T) +
    scale_color_manual(values = c("red", "blue")) + 
    guides(fill = guide_legend(reverse=TRUE)) + 
    scale_fill_discrete(name="No name", labels=c("A", "B")) + #Why does this line not work?
    coord_flip()
 p

为什么图例名称和变量名称不变?我该如何更改它们?

【问题讨论】:

  • 尝试将name="No name", labels=c("A", "B") 放入scale_color_manual() 而不是scale_fill_discrete() 可能吗?
  • 哇,是的,这行得通!惊人的!谢谢。

标签: r ggplot2 legend boxplot tidy


【解决方案1】:

这能解决您的问题吗?

library(ggplot2)
library(reshape)
mtcars <- melt(mtcars, id="am")
mtcars$am <- as.character(mtcars$am)
p <- ggplot(mtcars, aes(x = variable, y = value)) + 
  geom_boxplot(aes(color = am), width = 0.4, size = 0.4, position = position_dodge(0.6), 
               outlier.shape=NA, notch=T) +
  scale_color_manual(values = c("red", "blue"),
                     name="No name", labels=c("A", "B")) + 
  guides(fill = guide_legend(reverse=TRUE)) + 
  coord_flip()
p

问题是你没有在图中使用“填充”(你使用“颜色”),所以调整“填充”比例没有任何效果。

另外,将guides(fill = guide_legend(reverse=TRUE)) 更改为guides(color = guide_legend(reverse=TRUE)) 以反转图例顺序。

【讨论】:

  • 是的!完美的!非常感谢。 :)
猜你喜欢
  • 2022-08-23
  • 2017-01-06
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 2014-05-31
  • 2022-01-07
  • 1970-01-01
相关资源
最近更新 更多