【发布时间】:2019-09-23 11:11:17
【问题描述】:
我正在尝试将子图分组图例添加到 plotly 中的一系列 GROUPED 条形图。我发现了许多图表的子图分组图例示例(就像这里的最后一个图形示例:https://plot.ly/r/legend/),但我无法让“legendgroup = ~”方法适用于 GROUPED 条形图。
我有两个不同年份(2017 年和 2019 年)针对我公司的多个运营部门的调查数据。我想以分组条形格式分别并排显示每个运营单位的 2017 年和 2019 年调查结果,并为每个运营单位提供图表。唯一不起作用的元素是调查年度(2017 年或 2019 年)的图例,我想在所有图表中使用它。
library(data.table)
library(plotly)
# Dummy data
data <- data.table(Group = rep(c("Business_Unit_1","Business_Unit_2"), each = 4),
Question = rep(c("Happy","Ethics","Happy", "Ethics"), each = 2),
Year = c("2017", "2019", "2017", "2019", "2017", "2019", "2017", "2019"),
Prop = c(.9, .95, .8, .75, .7, .8, .8, .97))
# Grouped bar chart 1
plot_1 <- plot_ly() %>%
add_trace(x = ~ data[Group == "Business_Unit_1" & Year == "2017", (Question)],
y = ~ data[Group == "Business_Unit_1" & Year == "2017", (Prop)],
name = "2017",
type = 'bar',
marker = list(color = 'rgb(158,202,225)',
line = list(color = 'rgb(8,48,107)', width = 1.5))) %>%
add_trace(x = ~ data[Group == "Business_Unit_1" & Year == "2019", (Question)],
y = ~ data[Group == "Business_Unit_1" & Year == "2019", (Prop)],
name = "2019",
type = 'bar',
marker = list(color = 'rgb(58,200,225)',
line = list(color = 'rgb(8,48,107)', width = 1.5))) %>%
layout(yaxis = list(title = 'Proportion'),
annotations = list(x = 0.5 , y = 1.05, text = "Business_Unit_1", showarrow = F, xref = 'paper', yref = 'paper'),
barmode = 'group')
# Grouped bar chart 2
# Right now I am just hiding the second legend
plot_2 <- plot_ly() %>%
add_trace(x = ~ data[Group == "Business_Unit_2" & Year == "2017", (Question)],
y = ~ data[Group == "Business_Unit_2" & Year == "2017", (Prop)],
name = "2017",
type = 'bar',
showlegend = FALSE,
marker = list(color = 'rgb(158,202,225)',
line = list(color = 'rgb(8,48,107)', width = 1.5))) %>%
add_trace(x = ~ data[Group == "Business_Unit_2" & Year == "2019", (Question)],
y = ~ data[Group == "Business_Unit_2" & Year == "2019", (Prop)],
name = "2019",
type = 'bar',
showlegend = FALSE,
marker = list(color = 'rgb(58,200,225)',
line = list(color = 'rgb(8,48,107)', width = 1.5))) %>%
layout(yaxis = list(title = 'Proportion'),
annotations = list(x = 0.5 , y = 1.05, text = "Business_Unit_2", showarrow = F, xref = 'paper', yref = 'paper'),
barmode = 'group')
# Create the subplot
plots <- subplot(plot_1, plot_2, shareY = TRUE, nrows = 1)
plots
这段代码的编写方式,图例仅链接到第一个图,第二个图的图例被隐藏。有人可以帮忙吗?
【问题讨论】: