我正在使用plotly来创建类似下面的堆积条形图
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")
其次是因为我拥有的是动态表,所以var1和var2中只有一个值,所以它就像
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")
在这种情况下,图表不会显示。如果我在var1中有2个值 或者在var2中,图表仍然显示但不显示。有人能告诉我如何处理这个问题吗?
感谢, Manoj