使用 Plotly 和 R 而不使用 ggplot 的堆积面积图

kkd*_*d42 3 r plotly

有没有办法只在 R 中使用 plot_ly 制作堆积条形图?我知道一个可能的解决方案是使用 ggplot,然后使用 ggplotly 进行转换,但它看起来不像其他 plotly 图表那么好。该Plotly网站有一个例子,但是当一类是通过点击传说取出总数保持不变。

制作示例数据:

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)
Run Code Online (Sandbox Code Playgroud)

堆叠的酒吧工作:

# 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')
Run Code Online (Sandbox Code Playgroud)

我找不到折线图的“barmode = 'stack'”的类似物:

# Attempt with tidy data
df %>% 
  plot_ly(
    x = ~X, 
    y = ~Y, 
    color = ~GroupName, 
    type='scatter', 
    mode = 'lines', 
    fill = 'tonexty', 
    fillcolor = ~GroupName) 
Run Code Online (Sandbox Code Playgroud)

来自 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') 
Run Code Online (Sandbox Code Playgroud)

有没有人能够成功地做到这一点?谢谢!

编辑澄清:我知道可以先做一个 cumsum 然后创建图表,但仍然感谢回应!我想知道是否可以在图表中进行求和,使其表现得像堆叠条,单击图例删除一个组会显示其余组的总和。

ali*_*ire 5

您可以调整数据以使用该点的 y 值的累积总和来计算堆叠值,例如

library(plotly)
library(tidyverse)

       # group, sort (to keep cumulative sum in right order), and adjust Y
df %>% group_by(X) %>% arrange(GroupName) %>% mutate(Y = cumsum(Y)) %>% 
    plot_ly(type = 'scatter', x = ~X, y = ~Y, color = ~GroupName, 
            mode = 'lines', fill = 'tonexty')
Run Code Online (Sandbox Code Playgroud)

堆积的面积图