Search code examples
rplotlystacked-bar-chart

The R plot_ly stacked bar chart can only show multiple values with different colors


I am programming a R-application, where I need to visualize data in stacked bar-charts. So far everything works fine if there are multiple bars shown, but I am getting empty graphs when I want to show only one bar.

So I created different plots with some dummy data, that shows my problem. (The data is fictitious)

data <- data.table(FRUIT = c("apples", "bananas", "kiwis", "apples", "bananas", "kiwis"), 
                    KCALS = c(100, 200, 130, 100, 200, 130), 
                    DATE = as.Date(c("2022-10-01", "2022-10-01", "2022-10-01", "2022-10-02", "2022-10-03", "2022-10-03")))

dummy-data

The first graph shows an overview over multiple dates:

plot_ly(data, x = ~DATE, y = ~KCALS, color = ~FRUIT, type = "bar") %>%
    layout(yaxis = list(title = " "), xaxis = list(title = " "), barmode = "stack")

enter image description here

The second graph shows only one day:

plot_ly(data[DATE == "2022-10-01"], x = ~DATE, y = ~KCALS, type = "bar") %>%
    layout(yaxis = list(title = " "), xaxis = list(title = " "), barmode = "stack")

enter image description here

Ok, that worked. But if I enable the "color-option" again, the plot is empty:

plot_ly(data[DATE == "2022-10-01"], x = ~DATE, y = ~KCALS, color = ~FRUIT, type = "bar") %>%
    layout(yaxis = list(title = " "), xaxis = list(title = " "), barmode = "stack")

enter image description here

Why is it behaving like this? What am I doing wrong? And is there any documentation available, that really describes how the data gets processed in the plot_ly()- function?


Solution

  • When I run your code with color variable it does return a stacked bar plot for a single value. Make sure you don't overwrite variables and try it with a clean environment. Here is some reproducible code:

    library(data.table)
    data <- data.table(FRUIT = c("apples", "bananas", "kiwis", "apples", "bananas", "kiwis"), 
                       KCALS = c(100, 200, 130, 100, 200, 130), 
                       DATE = as.Date(c("2022-10-01", "2022-10-01", "2022-10-01", "2022-10-02", "2022-10-03", "2022-10-03")))
    library(plotly)
    plot_ly(data, x = ~DATE, y = ~KCALS, color = ~FRUIT, type = "bar") %>%
      layout(yaxis = list(title = " "), xaxis = list(title = " "), barmode = "stack")
    

    plot_ly(data[DATE == "2022-10-01"], x = ~DATE, y = ~KCALS, type = "bar") %>%
      layout(yaxis = list(title = " "), xaxis = list(title = " "), barmode = "stack")
    

    plot_ly(data[DATE == "2022-10-01"], x = ~DATE, y = ~KCALS, color = ~FRUIT, type = "bar") %>%
      layout(yaxis = list(title = " "), xaxis = list(title = " "), barmode = "stack")
    

    Created on 2023-02-16 with reprex v2.0.2


    Here you can find the docs about bar charts in plotly.