简体   繁体   中英

Display the legend inside the graph when wrapping with ggplot2

How can I do...

图例位于一小部分的备用角

... instead of the default ...

在此处输入图片说明

?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM