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.
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.
You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))
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.
Add this to your plot:
+ guides(colour = guide_legend(nrow = 1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With