有没有办法只使用R中的plot_ly制作堆积条形图?我知道可能的解决方案是use ggplot and then convert with ggplotly但它看起来不像其他情节图表那么好 . Plotly site有一个示例,但通过单击图例删除类别时总计保持不变 .
制作示例数据:
library(tidyverse)
library(plotly)
# Create some data
grpnames <- c("Thing_3", "Thing_2", "Thing_1")
xval <- as.factor(c(100, 101, 102, 103))
frame <- merge(grpnames, xval, all=T)
yval <- runif(12, 0, .2)
df <- tbl_df(cbind(frame, yval))
colnames(df) <- c("GroupName", "X", "Y")
df.wide <- spread(df, key = GroupName, value = Y)
堆叠棒工作:
# Creates a legit stacked bar where values sum to highest point
plot_ly(df, x = ~X, y = ~Y, color = ~GroupName, type='bar') %>%
layout(barmode = 'stack')
我找不到折线图的“barmode ='stack'”的模拟:
# Attempt with tidy data
df %>%
plot_ly(
x = ~X,
y = ~Y,
color = ~GroupName,
type='scatter',
mode = 'lines',
fill = 'tonexty',
fillcolor = ~GroupName)
此处尝试的Plotly方面的示例不会为X的每个值添加Y的值 - 它只是覆盖它们 .
# Attempt with wide data
df.wide %>%
plot_ly(
x = ~X,
y = ~Thing_1,
name = 'Thing 1',
type = 'scatter',
mode = 'none',
fill = 'tozeroy',
fillcolor = 'aquamarine') %>%
add_trace(
x = ~X,
y = ~Thing_2,
name = 'Thing 2',
fill = 'tonexty',
fillcolor = 'orange') %>%
add_trace(
x = ~X,
y = ~Thing_3,
name = 'Thing 3',
fill = 'tonexty',
fillcolor = 'gray')
有没有人能够成功地做到这一点?谢谢!
编辑澄清:我可以先做一个cumsum,然后创建图表,但仍然欣赏回复!我可以在图表中执行求和,使其行为类似于堆积条形图,其中单击图例以移除组显示其余组的总和 .
2 回答
您可以调整数据以使用该点的y值的累积和来计算堆积值,例如:
您可以通过将要堆叠的内容添加到一起来计算堆叠区域的高度 . 然后绘制这些已经堆积的累积值 . 来自原始问题的“可重现的”数据是不可重复的,因此我在这里展示了一些新的数据 .
请注意,在绘图页面上的示例中使用的数据也会转换为这样的累积表 - [https://plot.ly/r/filled-area-plots/#stacked-area-chart-with-cumulative-values]