0
votes

I use plotly library in R.

I want to have two symmetric bar charts. Something like that:

enter image description here

But I have :

enter image description here

plot_ly(x= customer_age_sex$POP,y=customer_age_sex$AGE,color=customer_age_sex$CIVILITE) %>% 
 add_bars(orientation = 'h')

How can I change the orientation of the orange bar plot to be symmetric with the other?

Thanks a lot for your help.

1
Please add a sample of the code you are using, reproducible data sample, etc.David Klotz

1 Answers

1
votes

There is a good example here. Note that this requires the values to be negative for one of the genders. If that is not the case, you could do the following:

set.seed(1)
age <- rep(1:90, 2)
sex <- rep(c('Monsieur', 'Madame'), each = 90)
pop <- rep(seq(100,11),2) + runif(180,0,10)

df <- data.frame(age, sex, pop) %>%
  mutate(abs_pop = pop) %>%
  mutate(pop =ifelse(sex=='Monsieur',-pop,pop))

df %>% 
  plot_ly(x= ~pop, y=~age,color=~sex) %>% 
  add_bars(orientation = 'h', hoverinfo = 'text', text = ~abs_pop) %>%
  layout(bargap = 0.1, barmode = 'overlay',
         xaxis = list(tickmode = 'array', tickvals = c(-1000, -500, 0, 500, 1000),
                      ticktext = c('1000', '500', '0', '500', '1000')))

enter image description here

Hope this helps!