I have a plot made with ggplot2 and I'd like to get the legend positioned in the top left corner.
legend.position = "top"
gets me a legend positioned above the plot, but centered:
legend.position = c(0,1)
gets the legend in the top left, but it floats over the other plot elements:
Know how to get that legend up in the top left without having it float? I tried declaring the legend height, but no dice. Do I have to adjust the size and position of the title and plot area?
Thanks!
position. You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left .
For Moving the position of ggplot2 legend at any side of the plot, we simply add the theme() function to geom_point() function.
In order to draw our legend outside of the plotting area, we can use a combination of the “topright” argument and an additional specification of inset. The “topright” argument specifies that the legend should be in the upper right corner of the graph.
You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))
It can be done with legend.justification using predefined options.
library(ggplot2)
ggplot(mtcars, aes(x=factor(cyl), y=mpg, fill=factor(cyl))) +
geom_boxplot() +
ggtitle("No title needed") +
theme(legend.position='top',
legend.justification='left',
legend.direction='horizontal')
How about something like this -- not sure if there's a way to avoid the "hack" of \n\n\n
in the call to ggtitle()
library(ggplot2)
ggplot(mtcars, aes(x = factor(cyl), y = mpg, fill = factor(cyl))) +
geom_boxplot() +
ggtitle("A Title for Plot\n\n\n") +
theme(
legend.position = c(0, 1),
legend.justification = c(0, 0),
legend.direction = "horizontal"
)
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