I'm trying to make an interactive side-by-side bar chart where one shows the grouped one and the other shows the percentage.
library(plotly)
Animals <- c("giraffes", "orangutans", "monkeys")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
data <- data.frame(Animals, SF_Zoo, LA_Zoo)
#Stacked bar
fig1 <- plot_ly(data, x = ~Animals, y = ~SF_Zoo, type = 'bar', name = 'SF Zoo')
fig1 <- fig1 %>% add_trace(y = ~LA_Zoo, name = 'LA Zoo')
fig1 <- fig1 %>% layout(yaxis = list(title = 'Count'), barmode = 'stack')
#Group
fig2 <- plot_ly(data, x = ~Animals, y = ~SF_Zoo, type = 'bar', name = 'SF Zoo')
fig2 <- fig2 %>% add_trace(y = ~LA_Zoo, name = 'LA Zoo')
fig2 <- fig2 %>% layout(yaxis = list(title = 'Count'), barmode = 'group')
subplot(fig1, fig2)
Individually they work, but when I use subplot, either all of the bars seemed to go to 'grouped' version or they go to 'stacked' like so:
Are there any fixes for this? I'm not even sure why the code is no working.
Changing the legend isn't going to let you have a stacked and dodged bar chart in the same
subplot. One of the limitations ofsubplotis that there is only one layout. That means there can be only onebarmode. There are still a lot of different ways that you could should these two plots side by side, though.By the way, you wrote that one of the two was percentages, but neither plot is set that way.
Here is one way you can make this happen. I used the library
htmltools.