Justin Dhindsa
Justin Dhindsa

Reputation: 109

ggplot bar graph with flipped direction of bars

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?

Upvotes: 2

Views: 596

Answers (1)

Vinícius Félix
Vinícius Félix

Reputation: 8811

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

Upvotes: 2

Related Questions