Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plotly stacked bar chart with over 100 categories

I have a dataset that contains over 100 categories. If I am going to plot it, I have to write over 100 lines code for it. Here is the example from plotly official website:

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)
p <- plot_ly(data, x = ~Animals, y = ~SF_Zoo, type = 'bar', name = 'SF Zoo') %>%
add_trace(y = ~LA_Zoo, name = 'LA Zoo') %>%
layout(yaxis = list(title = 'Count'), barmode = 'stack')

As you can see, if I have over 100 zoos that are going to be plotted, I need to write add_trace for over 100 times, which is inefficient. Does anyone know of ways to simplify it? I tried using for loop but I failed.

Or if anyone know how to use ggplotly to transfer a ggplot to an interactive format, it will also solve my problem. The plot produced by ggplot is a stacked grouped bar chart which x-axis have 10 facet_grid and about 100 categories in each grid. I tried using ggplotly directly and save it as an .html, however the plot's scale is very weird. It should looks like a rectangular with width about 40 and height about 8, but in html, it just shows like a square which is unreadable.

like image 510
Eleanor Avatar asked Jul 05 '17 15:07

Eleanor


People also ask

What is a 100% stacked bar chart?

In a 100% stacked bar chart, the bars are split into colored bar segments placed on top of each other. Each bar height is 100%, and the colored bar segments represent the components' relative contributions to the total bar.

How do you make a stacked bar graph in plotly?

To make this bar chart a stacked bar chart, go to the property 'Barmode' under 'Bar Size and Spacing' and select 'Stack' as the bar mode from the dropdown list. To set the plot title, go to the 'General' section under the 'Style' menu and type in the plot title within the textbox provided under 'Title'.


1 Answers

You can melt the data and then plot them like below:

library(data.table)  
library(plotly)

data.table::melt(data, id.vars='Animals') %>%
plot_ly(x = ~Animals, y = ~value, type = 'bar', 
                name = ~variable, color = ~variable) %>%
      layout(yaxis = list(title = 'Count'), barmode = 'stack')

This will plot:

enter image description here

like image 198
M-- Avatar answered Oct 22 '22 22:10

M--