I am using plotly to create a stacked bar chart something like below
df <- data.frame(
var1 = c("NY", "NY", "NY", "SFO", "SFO", "SFO"),
var2 = c("Low", "Medium", "High", "Low", "Medium", "High"),
value = c(10,15,20,10,20,25)
)
df$var2 <- factor(df$var2, levels = c("Low","Medium","High"))
# sort the factor table
df <- arrange(df, var2)
col <- list(
color = ifelse(
df$var2 == "Low",
"steelblue",
ifelse(
df$var2 == "Medium",
"darkorange",
"olivedrab"
)
))
# Plot
plot_ly(
df,
x = ~ var1,
y = ~ value,
color = ~ var2,
marker = col,
type = "bar"
) %>% layout(barmode = "stack")
There are 2 issues I am facing: First is that the legend is not coming correctly (see image).
Second is that since what I have is a dynamic table, there is a possibility that there is only one value in var1 and var2 so it will be something like
df <- data.frame(var1 = c("NY"),
var2 = c("Low"),
value = c(10))
df$var2 <- factor(df$var2, levels = c("Low", "Medium", "High"))
# sort the factor table
df <- arrange(df, var2)
col <- list(color = ifelse(
df$var2 == "Low",
"steelblue",
ifelse(df$var2 == "Medium",
"darkorange",
"olivedrab")
))
# Plot
plot_ly(
df,
x = ~ var1,
y = ~ value,
color = ~ var2,
marker = col,
type = "bar"
) %>% layout(barmode = "stack")
in which case the chart doesn't show up. If I have 2 values either in var1 or in var2 the chart still shows up but not with one. Can someone tell me how to handle this?
thanks, Manoj