'ggplot2 legend items in a single horizontal row
It seems that the code I wrote and tested last week has now suddenly decided to change the output even though nothing in the code or the version of R or Rstudio has changed.
Previously when I drew a plot with ggplot2 and asked for the legend to appear at the bottom of the plot, it automatically oriented the items into a single horizontal row. Now when I run the same code it places the item in a number of 2-row columns.
Here's an example:
mtcars$cyl <- (1:32)
subcars <- subset(mtcars, cyl<10)
subcars$cyl <- as.factor(subcars$cyl)
ggplot(subcars, aes(carb, mpg, group=cyl, colour=cyl)) +
geom_line() +
theme_classic() +
theme(plot.title = element_text(size = rel(2), face="bold", vjust=-4)) +
theme(legend.position = "bottom") +
theme(legend.direction = "horizontal") +
labs(title="Title")
As you can see, I have already tried adding in the line theme(legend.direction = "horizontal")
but I still get a legend which displays the items in 5 2-row columns (yes, its not even just in two rows).
Now I can only assume that there has been some update that I was not aware of or something, so I'm willing to accept that I need to come up with a new strategy for dealing with this problem (which just wasn't a problem last week). Although I am a little bit confused about why my code has suddenly decided to stop working (any input on this welcome), I'm more interested in finding a fix for the immediate problem of my legend items being displayed in a strange configuration.
Solution 1:[1]
Add this to your plot:
+ guides(colour = guide_legend(nrow = 1))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | joran |