1

I am trying to create a graph similar to the one in this picture.

You can see that they have flipped the direction of the blue bars even though they have positive x values. Right now, I am able to reproduce that bar graph but with the bars in the same direction. Is it possible to create this same type of graph in ggplot with the flipped bars and positive x values?

  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. – MrFlick Sep 07 '21 at 18:37
  • 1
    See here to color positive/negative bars different colors: https://stackoverflow.com/questions/48463210/how-to-color-code-the-positive-and-negative-bars-in-barplot-using-ggplot. You can also use coord_flip to rotate it. Need to do a bit of extra work for the labels and those split axes are very un-ggplot like so if that's important that will be some extra work. – MrFlick Sep 07 '21 at 18:39
  • Please provide enough code so others can better understand or reproduce the problem. – Community Sep 07 '21 at 18:51

1 Answers1

1

Here is a tidyverse solution

Libraries

library(tidyverse)

Data

    df <-
      tibble(
        y  = letters[1:15],
        p = runif(15,5,100),
        g = as.factor(rep(0:1,c(5,10)))
      )

Code

df %>% 
  #Create auxiliary variable, where for a determined group the percentage become negative
  mutate(
    p2 = if_else(g == 0, -p,p),
    y = fct_reorder(y,p2)
    ) %>% 
  ggplot(aes(p2,y, fill = g))+
  geom_col()+
  scale_x_continuous(
    breaks = seq(-100,100,10),
    #Make the labels positive
    labels = seq(-100,100,10) %>% abs()
    )

Output

enter image description here

Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32