-1

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.

Peter Rowan
  • 127
  • 1
  • 11
  • So what is the problem exactly? What is missing from the ggplot guide? – erocoar Feb 23 '18 at 20:34
  • Hi erocoar, the legend with boxplot symbol takes too much space in a graph. Imagine if you have more than ten data set, it will take a few rows to show the legend. Thanks. – Peter Rowan Feb 23 '18 at 21:07

1 Answers1

2

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, e.g., 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")

enter image description here

erocoar
  • 5,723
  • 3
  • 23
  • 45