使用 ggplot2 包装时在图表内显示图例

Display the legend inside the graph when wrapping with ggplot2

我该怎么做...

...而不是默认的...

?

我为此使用 diamonds 数据集。您可以使用 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))

输出:

本质上,theme(legend.position=c(.8,.15)) 取两个值,范围从 0 到 1,一个用于 x 轴,一个用于 y 轴。 0 表示将图例放在轴的开头,而 1 表示放在轴的末尾。

如果您愿意,可以查看 cookbook,那里有更多示例。

此外,根据@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))