0

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

Tomasge
  • 11
  • 2
  • You need to make a separate dataframe with values for the yintercept and the faceting variable, then reference that separate dataframe in `geom_hline()`. See [this question](https://stackoverflow.com/questions/35322711/drawing-vertical-lines-of-different-value-in-ggplot-facets) and [this one](https://stackoverflow.com/questions/17187287/ggplot2-add-geom-line-for-each-facet-in-bland-altman-plot) – Jan Boyer Sep 25 '18 at 19:22
  • Possible duplicate of [How to add different lines for facets](https://stackoverflow.com/questions/11846295/how-to-add-different-lines-for-facets) – Jan Boyer Sep 25 '18 at 19:24
  • @JanBoyer Aren’t you referring to a data frame like vline in the code above? – Tomasge Sep 25 '18 at 19:40
  • caused by typo `varaible` in vlines def – dww Sep 25 '18 at 19:52
  • @dww Thank you dww, it solved it!! Hope this serves now as a workable example for future questions on the topic. As they say, there is nothing more deceptive than an obvious fact – Tomasge Sep 25 '18 at 20:26
  • @Tomsage, you can post an answer and accept it. – Artem Sep 26 '18 at 08:26

1 Answers1

0

Correct the typo in defining vlines. It should say VARAIBLE 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)
Tomasge
  • 11
  • 2