【问题标题】:Can't add different lines to different facets in geom_bar()无法在 geom_bar() 中将不同的行添加到不同的方面
【发布时间】:2019-03-01 11:56:01
【问题描述】:

我正在尝试在 ggplot 中的 geom_bar() 的不同方面添加不同的行。我能够复制此处发布的解决方案,但无法让我的工作。非常感谢您的帮助!

这是我的数据库:

> rbind(head(mlt1), tail(mlt1))

      Group variable value
1       USA     CGDP 0.639
2       JPN     CGDP 0.523
3       CHN     CGDP 0.576
4       GER     CGDP 0.413
5     OEDCE     CGDP 0.504
6   BENELUX     CGDP 0.257
91  SWI_POL     CRES 0.115
92   SA_NIG     CRES 0.033
93  IRAN_PK     CRES 0.082
94    SAUDI     CRES 0.169
95 SOUTH_AM     CRES 0.054
96 CONG_SEN     CRES 0.025 

我使用以下代码来创建情节:

vlines <- data.frame(varaible=levels(mlt1$variable), yval=c(0.5, 0.3, 0.15, 0.05))

ggplot(mlt1, aes(x=Group, y=value, fill=variable)) +
            geom_bar(stat="identity", position="dodge") + coord_flip() +
            facet_grid(.~variable) +
            theme(legend.position = "none", 
                  axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5)) +
            geom_hline(aes(yintercept=yval), data=vlines)

我得到的这个图在每个方面重复 5 条线,而不是在每个方面绘制一条线(即在方面 1 中为 0.5,在方面 2 中为 0.3,等等):

【问题讨论】:

  • 您需要使用 yintercept 和 faceting 变量的值创建一个单独的数据框,然后在 geom_hline() 中引用该单独的数据框。见this questionthis one
  • @JanBoyer 上面的代码中不是指像 vline 这样的数据框吗?
  • 由 vlines def 中的拼写错误 varaible 引起
  • @dww 谢谢dww,解决了!!希望这现在可以作为未来有关该主题的问题的可行示例。正如他们所说,没有什么比一个明显的事实更具欺骗性了

标签: r ggplot2 facet geom-bar geom-hline


【解决方案1】:

更正定义vlines 中的错字。它应该说 VARAIBLE 而不是 VARAIBLE。正确的代码是:

vlines <- data.frame(variable=levels(mlt1$variable), yval=c(0.5, 0.3, 0.15, 0.05))

ggplot(mlt1, aes(x=Group, y=value, fill=variable)) +
        geom_bar(stat="identity", position="dodge") + coord_flip() +
        facet_grid(.~variable) +
        theme(legend.position = "none", 
              axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5)) +
        geom_hline(aes(yintercept=yval), data=vlines)

【讨论】:

    猜你喜欢
    • 2019-01-17
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 2021-11-19
    相关资源
    最近更新 更多