Home > Mobile >  Plotly stacked bar chart
Plotly stacked bar chart

Time:01-17

May I ask you for your help, please? I am trying to make a stacked bar chart with plot_ly() from this dataset: enter image description here

CodePudding user response:

In barmode = 'stack' the positive and negative values ​​are overlaping each other.

Here is an example dataset:

df <- data.frame(TimePeriod = rep(as.Date(c("2022-01-01", "2022-01-02", 
                                            "2022-01-03", "2022-01-04",
                                            "2022-01-05")), 3),
                 DataValue_per_GDP = c(1, 3, 5, 4,7,
                                       3,-2, 1,-4,0,
                                       2, 3, 2,-1,1),
                 Sectors = rep(c(LETTERS[1:3]), each = 5))

For the date "2022-01-02" we have the following values:

  TimePeriod DataValue_per_GDP Sectors
1 2022-01-02                 3       A
2 2022-01-02                -2       B
3 2022-01-02                 3       C

The first bar A starts at 0 up to 3. The bar B starts at the value 3 and goes two values down to 1. Bar C starts at 1 und goes 3 values up to 4. So the bars overwrite each other and the result looks like this:

enter image description here

To correct this behavior try barmode = 'relative'.

plotly::plot_ly(df, 
                x=~TimePeriod, 
                y=~round(DataValue_per_GDP,2), 
                color=~Sectors, 
                type = "bar") %>% 
  layout(xaxis = list(title = ""), 
         yaxis = list(title = "(% of GDP)"), 
         barmode = 'relative')

enter image description here

CodePudding user response:

After reshaping the data with pivot_wider we could use add_trace with the different columns:

library(plotly)
library(dplyr)
library(tidyr)

df1 <- df %>%
  mutate(Sectors = trimws(Sectors)) %>% 
  pivot_wider(names_from = Sectors, values_from = DataValue_per_GDP) 

fig <- plotly::plot_ly(df1, x=~TimePeriod, y=~round(`C. External`*100,2), 
                type = "bar", name="C. External") %>% 
  add_trace(y = ~`B. Private`, name = 'B. Private') %>% 
  add_trace(y = ~`A. General government`, name = 'A. General government') %>% 
  layout(yaxis = list(title = '(% of GDP)'), barmode = 'stack')
fig

enter image description here

  • Related