Can't add different lines to different facets in geom_bar()

531 views Asked by At

I'm trying to add different lines to different facets in geom_bar() in ggplot. I'm able to replicate solutions posted here but can't get mine to work. Help greatly appreciated!

Here is my database:

> 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 

I use the following code to create the plot:

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)

I get this plot that repeats the 5 lines in each facet instead of drawing one line in each facet (ie at 0.5 in facet 1, 0.3 in facet 2, etc):

ggplot image with repeated lines in each facet

1

There are 1 answers

0
Tomasge On

Correct the typo in defining vlines. It should say VARIABLE and not VARAIBLE. The correct code is:

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)