【发布时间】:2017-06-13 19:39:49
【问题描述】:
有没有办法只在 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 然后创建图表,但仍然感谢回复!我想知道是否可以在图表中进行求和,使其表现得像堆叠的条形图,单击图例删除组会显示剩余组的总和。
【问题讨论】: