r - 使用不带 ggplot 的 Plotly 和 R 堆积面积图

标签 r plotly

有什么方法可以只使用 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 然后创建图表,但仍然感谢您的回复!我想知道是否可以在图表内进行求和,使其表现得像堆叠条,点击图例删除一个组会显示剩余组的总和。

最佳答案

您可以调整数据以使用该点的 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')

stacked plotly area plot

关于r - 使用不带 ggplot 的 Plotly 和 R 堆积面积图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41905565/

相关文章:

r - 使用 R 合并重复的列

r - 来自 ggpol 的facet_share 创建了太大的边距

r - 将 ggplot2 转换为 ggplotly 时缺少 geom_rect

r - 在 plotly scatter3D 中改变颜色

r - 如何使用 R 中的 k-means 聚类技术获得与数据相对应的聚类编号?

r - 如何在 R 中仅显示带标签的数据框中的一种类型的属性

r - 在 R 的函数中只能将字符串转换为符号

python - 如何使用 Python Plotly 制作三元等高线图?

r - 公共(public)轴子图与 plot.ly for R

r - 如何在shiny或flexdashboard中制作用户选择的变量的图表?