简体   繁体   中英

How to change boxplot legend style in ggplot2

The boxplot legend style takes too much space in my graph. I wonder if the legend style in ggplot2 can be changed as in the base package. I enclosed the current legend style in ggplot2 http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/ and I want to change a different style like a line, box or circle as shown in the link http://www.sthda.com/english/wiki/add-legends-to-plots-in-r-software-the-easiest-way . Please look at example 2 at the end of the page. Thank you.

So, this can be done but needs some work-around: Plot points (or another geom) with size -1 and use their legend that you can actually edit. Consider, eg, this

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")

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM