当我只有一条曲线添加到plotly
堆积条形图时,缺少图例。
我的数据集如下:
myDF <- structure(list(Year = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "2017", class = "factor"),
Month = c("Mar", "Mar", "Mar", "Apr", "Apr", "Apr"), Date = structure(c(17241,
17242, 17242, 17259, 17260, 17261), class = "Date"), Quarter = c("Q1",
"Q1", "Q1", "Q2", "Q2", "Q2"), Week = structure(c(2L, 2L,
2L, 3L, 3L, 3L), .Label = c("2017-03-05", "2017-03-12", "2017-04-02"
), class = "factor"), NPS = structure(c(NA, NA, NA, 3L, 3L,
3L), .Label = c("Detractor", "Passive", "Promoter"), class = "factor")), .Names = c("Year",
"Month", "Date", "Quarter", "Week", "NPS"), row.names = 7:12, class = "data.frame")
根据用户选择,我根据Week
,Month
,Quarter
或Year
过滤此数据集。
这个代码就是其中之一:
myDF %>% select(one_of(c("Week","NPS"))) -> myDF
myDF %>% select(one_of(c("Month","NPS"))) -> myDF
myDF %>% select(one_of(c("Quarter","NPS"))) -> myDF
myDF %>% select(one_of(c("Year","NPS"))) -> myDF
colnames(myDF)[1] <- "Group"
对于情节,这是我的代码:
dcast(na.omit(melt(myDF, id.vars = 'Group')), Group ~ value, fun.aggregate = length) -> tab
tab
# Group Promoter
#1 2017-04-02 3
x <- list(
title = ""
)
y <- list(
title = "Count"
)
p <- plot_ly(tab, x = ~Group)
if ("Detractors" %in% colnames(tab[-1])){
p <- add_trace(p, y = ~`Detractors`, name = 'Detractors', type = 'bar',
marker = list(color = '#D52728')) #red
}
if ("Passive" %in% colnames(tab[-1])){
p <- add_trace(p, y = ~`Passive`, name = 'Passive', type = 'bar',
marker = list(color = '#1F78B4')) #orange
}
if ("Promoter" %in% colnames(tab[-1])){
p <- add_trace(p, y = ~`Promoter`, name = 'Promoter', type = 'bar',
marker = list(color = '#2BA02D')) #green
}
p <- layout(p, xaxis = x, yaxis = y, barmode = 'stack', legend = list(orientation = 'h'))
p
这是我得到的情节。在这种情况下,我没有看到任何图例,因为只有一条迹线 - Promoter
但是,如果使用具有多个跟踪的数据集(如下所示)并执行相同的步骤,我会得到图例。
myDF <- structure(list(Year = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "2017", class = "factor"),
Month = c("Mar", "Mar", "Mar", "Apr", "Apr", "Apr"), Date = structure(c(17241,
17242, 17242, 17259, 17260, 17261), class = "Date"), Quarter = c("Q1",
"Q1", "Q1", "Q2", "Q2", "Q2"), Week = structure(c(2L, 2L,
2L, 3L, 3L, 3L), .Label = c("2017-03-05", "2017-03-12", "2017-04-02"
), class = "factor"), NPS = structure(c(NA, NA, NA, 2L, 3L,
3L), .Label = c("Detractor", "Passive", "Promoter"), class = "factor")), .Names = c("Year",
"Month", "Date", "Quarter", "Week", "NPS"), row.names = 7:12, class = "data.frame")
当数据中只有一条迹线可用于识别颜色时,有没有办法显示图例?