Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 legend items in a single horizontal row

Tags:

r

legend

ggplot2

This may seem like a stupid question, but I am a little confused.

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.

like image 505
Psychologeek Avatar asked Mar 18 '16 14:03

Psychologeek


People also ask

How do I change the legend position in R?

Control legend position with legend. To put it around the chart, use the legend. position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.

How do I change the legend value in ggplot2?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))

How do you make a legend smaller in R ggplot2?

To change the Size of Legend, we have to add guides() and guide_legend() functions to the geom_point() function. Inside guides() function, we take parameter color, which calls guide_legend() guide function as value.


1 Answers

Add this to your plot:

+ guides(colour = guide_legend(nrow = 1)) 
like image 75
joran Avatar answered Oct 07 '22 15:10

joran