Elements of the ggplot2 legend in one horizontal line

This may seem like a silly question, but I'm a little confused.

It seems that the code I wrote and tested last week, now suddenly decided to change the output, even if nothing in the code or version of R or Rstudio has changed.

Previously, when I drew a plot with ggplot2 and asked to show the legend at the bottom of the graph, it automatically oriented the elements in one horizontal line. Now, when I run the same code, it puts the item in the number of columns of 2 rows.

Here is 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 already tried to add the theme(legend.direction = "horizontal") line theme(legend.direction = "horizontal") , but I still get a legend that displays elements in 5 columns of 2 rows (yes, it’s not even in two rows).

Now I can only assume that there was some kind of update that I did not know about or something like that, so I agree that I need to come up with a new strategy to solve this problem (which simply wasn’t a problem on last week). Although I'm a little confused about why my code suddenly decided to stop working (any input of this greeting), I'm more interested in finding a fix for an immediate problem with my legendary items displayed in a strange configuration.

+8
r ggplot2 legend
source share
1 answer

Add this to your plot:

 + guides(colour = guide_legend(nrow = 1)) 
+20
source share

All Articles