I use the diamonds
data set for this. You could use the theme(legend.position=
to do it:
ggplot(diamonds, aes(carat, price, fill = ..density..)) +
xlim(0, 2) + stat_binhex(na.rm = TRUE) + theme(aspect.ratio = 1) +
facet_wrap(~ color) + theme(legend.position=c(.8,.15))
Output:
Essentially, theme(legend.position=c(.8,.15))
takes two values that range from 0 to 1, one for the x-axis and one for the y-axis. 0 means place the legend at the beginning of the axis whereas 1 means at the end of the axis.
You can have a look at the cookbook if you like where there are more examples.
Also as per @Roland 's comment using the following with legend.justification
will probably position it even better:
ggplot(diamonds, aes(carat, price, fill = ..density..)) +
xlim(0, 2) + stat_binhex(na.rm = TRUE) + theme(aspect.ratio = 1) +
facet_wrap(~ color) + theme(legend.position = c(1, 0), legend.justification = c(1, 0))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.