有什么方法可以只使用 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')
关于r - 使用不带 ggplot 的 Plotly 和 R 堆积面积图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41905565/