Is there any way to make a stacked bar chart only using plot_ly in R? I’m aware a possible solution is to use ggplot and then convert with ggplotly but it doesn’t look as nice as other plotly charts. The Plotly site has an example, but the totals stay the same when a category is removed via clicking on the legend.
Make example data:
library(tidyverse) library(plotly) # Create some data grpnames <- c("Thing_3", "Thing_2", "Thing_1") xval <- as.factor(c(100, 101, 102, 103)) frame <- merge(grpnames , xval, all=T) yval <- runif(12, 0, .2) df <- tbl_df(cbind(frame, yval)) colnames(df) <- c("GroupName", "X", "Y") df.wide <- spread(df, key = GroupName, value = Y)
The stacked bar works:
# Creates a legit stacked bar where values sum to highest point plot_ly(df, x = ~X, y = ~Y, color = ~GroupName, type='bar') %>% layout(barmode = 'stack')
I couldn’t find an analogue to “barmode = ‘stack’” for a line chart:
# Attempt with tidy data df %>% plot_ly( x = ~X, y = ~Y, color = ~GroupName, type='scatter', mode = 'lines', fill = 'tonexty', fillcolor = ~GroupName)
And the example from the Plotly side, attempted here, doesn’t add the values of Y for each value of X – it simply overlays them.
# Attempt with wide data df.wide %>% plot_ly( x = ~X, y = ~Thing_1, name = 'Thing 1', type = 'scatter', mode = 'none', fill = 'tozeroy', fillcolor = 'aquamarine') %>% add_trace( x = ~X, y = ~Thing_2, name = 'Thing 2', fill = 'tonexty', fillcolor = 'orange') %>% add_trace( x = ~X, y = ~Thing_3, name = 'Thing 3', fill = 'tonexty', fillcolor = 'gray')
Has anyone been able to do this successfully? Thanks!
Edit for clarification: I’m looking to leverage plotly’s ability to sum on the fly, as with the stacked bars, rather than doing a cumsum beforehand.