首页 > 解决方案 > 无法更改 ggplot 箱线图图例名称

问题描述

我正在使用这段代码:

 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

为什么图例名称和变量名称不变?我怎样才能改变它们?

标签: rggplot2legendboxplottidy

解决方案


这能解决你的问题吗?

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

示例_1.png

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

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


推荐阅读