如何在ggplot2中更改boxplot图例样式

时间:2018-02-23 20:31:29

标签: r ggplot2 boxplot

boxplot图例样式在我的图表中占用了太多空间。我想知道ggplot2中的图例样式是否可以像在基础包中那样进行更改。我将当前的图例样式包含在ggplot2 http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/中,我想要更改链接http://www.sthda.com/english/wiki/add-legends-to-plots-in-r-software-the-easiest-way中显示的不同样式,如线,框或圆。请查看页面末尾的示例2。谢谢。

1 个答案:

答案 0 :(得分:2)

所以,这可以完成但需要一些解决方法:绘制大小为-1的点(或其他geom)并使用他们可以实际编辑的图例。考虑一下,例如,

library(ggplot2)
ggplot(mtcars, aes(x = factor(cyl), y = mpg, color = factor(cyl))) + 
  geom_point(size = -1, aes(fill = factor(cyl))) + 
  geom_boxplot(show.legend = FALSE) +
  scale_color_manual(name = "Number of Cylinders", values = c("blue", "red", "green")) +
  scale_fill_manual(name = "Number of Cylinders", values = c("blue", "red", "green")) +
  guides(colour = guide_legend(title.position = "top",
                               keywidth = unit(1, "cm"),
                               keyheight = unit(1, "cm"),
                               override.aes = list(shape = 22,
                                                   size = 10))) +
  theme(legend.position = c(0.14, 0.1),
        legend.direction = "horizontal") +
  labs(x = "Cylinders", y = "Miles/(US) gallon")

enter image description here