简体   繁体   English

用ggplot2包装时,在图内显示图例

[英]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. 我为此使用了diamonds数据集。 You could use the theme(legend.position= to do it: 您可以使用theme(legend.position=来做到这一点:

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. 本质上, theme(legend.position=c(.8,.15))取两个值,范围从0到1,一个用于x轴,一个用于y轴。 0 means place the legend at the beginning of the axis whereas 1 means at the end of the axis. 0表示将图例放在轴的起点,而1表示在轴的终点。

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: 同样根据@Roland的注释,在legend.justification使用以下内容可能会使其位置更好:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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