Praveen Singh Praveen Singh - 19 hours ago 2
R Question

Positioning the Legend Box

I have a bar Plot that looks like this:
enter image description here

If I use the command

legend.position=c(1,1),legend.justification=c(1,1)
then I get the plot like this:
enter image description here

But in this case the legend overlaps the plot. I want that the legend just shifts upwards without overlapping as in the first plot. What should I do ?

Answer

You can try this:

theme(legend.justification = "top")

Example:

mtcars$gear = factor(mtcars$gear)
mtcars$cyl = factor(mtcars$cyl)
p = ggplot(data = mtcars, aes(x=gear, fill=cyl) ) + geom_bar()
p = p + xlab("Gears") + ggtitle("Cylinders by Gears")
p = p + theme(legend.justification = "top")

p