【问题标题】:Display the legend inside the graph when wrapping with ggplot2用 ggplot2 换行时显示图表内的图例
【发布时间】:2015-12-01 14:21:43
【问题描述】:

我该怎么办...

...而不是默认...

?

【问题讨论】:

    标签: r ggplot2 legend facet facet-wrap


    【解决方案1】:

    我为此使用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))
    

    【讨论】:

    • 可能还要调整legend.justification,即theme(legend.position = c(1, 0), legend.justification = c(1, 0))
    • 是的,谢谢@Roland。我将添加指向食谱的链接,其中还提到了legend.justification 参数。
    • 我想除了调整这 4 个参数之外别无他法?
    • 我不知道@Arthur。你总是需要调整一些参数才能做你想做的事。 theme(legend.position = c(1, 0), legend.justification = c(1, 0)) 会一直放在右下角。
    • 只是当图例不覆盖内容时,最好将图例放在情节内部而不是外部。所以当有一些空闲空间时,我猜这可以内置......
    猜你喜欢
    • 2023-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多