无法在geom_bar()中向不同的面添加不同的线

问题描述 投票:0回答:1

我正在尝试在 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,等等):

ggplot image with repeated lines in each facet

r ggplot2 facet geom-bar geom-hline
1个回答
0
投票

更正定义

vlines
时的拼写错误。它应该显示 VARIABLE 而不是 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)
© www.soinside.com 2019 - 2024. All rights reserved.