我必须使用下面的数据
创建一个堆积条形图df <- data.frame(
var1 = c("NY", "NY", "NY", "SFO", "SFO", "SFO"),
var2 = c("LOW", "Medium", "High", "Low", "Medium", "High"),
value = c(10, 15, 20, 15, 20, 15)
)
基本上,x轴将为var1提供2个条形,并为每个var2填充值。在ggplot中你可以使用var2作为填充但我无法弄清楚如何在plotly中这样做。
有人可以帮忙吗?
感谢,
的Manoj
答案 0 :(得分:0)
您可以尝试:
# Split the data
df_list <- split(df, df$var2)
# plot the data and add the traces for var2
plot_ly(df_list$Low, x=~var1, y=~value, type="bar", name="Low") %>%
add_trace(y= df_list$Medium$value , name = "Medium") %>%
add_trace(y= df_list$High$value, name = "High") %>%
layout(barmode = "stack")
# A faster way would be something like this:
# First order var2
df$var2 <- factor(df$var2,levels = c("Low", "Medium", "High"))
# Plot
plot_ly(df, x= ~var11, y= ~value, color= ~var2, type="bar") %>% layout(barmode = "stack")
后期解决方案未正确显示图例中的颜色,这似乎是情节版plotly_4.5.2
中的错误。在xaxis上绘制两个以上的条形图是没有任何问题的。尝试使用三个var1
组的数据:
df2 <- data.frame(
var1 = c("NY", "NY", "NY", "SFO", "SFO", "SFO","Test"),
var2 = c("Low", "Medium", "High", "Low", "Medium", "High","Low"),
value = c(10, 15, 20, 15, 20, 15,30)
)
plot_ly(df2, x=~var1, y=~value, color=~var2, type="bar") %>% layout(barmode = "stack")
# Or use ggplot
library(ggplot2)
p <- ggplot(df, aes(x=var1, y=value, fill=var2)) + geom_bar(stat="identity") + theme_bw()
ggplotly(p)