2

Code:

library(plotly)
library(tidyverse)

df <- data.frame(protein = c("Chicken", "Beef", "Pork", "Fish",
                             "Chicken", "Beef", "Pork", "Fish"),
                 y1 = c(3, 24, 36, 49, 7, 15, 34, 49),
                 y2 = c(9, 28, 40, 47, 8, 20, 30, 40 ), 
                 gender = c("Male", "Male", "Male", "Male",
                            "Female", "Female", "Female", "Female"))

df %>%
  plot_ly() %>% 
  add_bars (y = ~y1, x = ~protein,
            name = 'y1.male') %>% add_bars(y = ~y2,
               x=~protein, color = I("green"),name = "y2.male")%>%
  add_bars(y = ~y1, x = ~protein, color = I("black"),
           name = 'y1.female') %>% add_bars(y = ~y2,
                x=~protein, color = I("red"), name = "y2.female")

My desired result is to create something similar to this:

enter image description here

However when you run the code, you'll see that it has stacked the "Male" and "Female" values in each bar. I would like "y1.male" to represent the "Male" data when y = y1, "y2.male" to represent the "Male" data when y = y2, "y1.female" to represent the "Female" data when y = y1, and "y2.female" to represent the "Female" data when y = y2, respectively. How can I go about doing this without having to use filter by "transforms" in r-plotly?

M--
  • 25,431
  • 8
  • 61
  • 93
  • Would you clarify what do you mean by *[filter by "transforms"]*? – M-- Apr 06 '22 at 18:11
  • 1
    @M-- Yeah! it actually relates to my post from yesterday- [link](https://stackoverflow.com/questions/71746433/why-doesnt-method-update-work-when-using-transforms-to-filter-in-r-plotly). The link to the example code is provided there. I was trying to create a dropdown menu by filtering (using transforms), but couldn't get it to work. So I'm exploring alternative methods. – serenity476 Apr 06 '22 at 18:31

1 Answers1

2

We can rearrange the data to be in long format and then plot it:

df %>% 
  pivot_longer(cols = c(y1, y2)) %>% 
  unite(gender_var, c(gender, name)) %>% 
 plot_ly() %>% 
  add_bars (x = ~protein, y = ~value,
            name = ~gender_var)

M--
  • 25,431
  • 8
  • 61
  • 93