plotly R:保留分类列名称,但不要绘制它们
plotly R: keep categorical column names, but don't plot them
有了这个对象:
fullDT <-
structure(list(QuarterAndYear = structure(1:12, .Label = c("2015 Q1",
"2015 Q2", "2015 Q3", "2015 Q4", "2016 Q1", "2016 Q2", "2016 Q3",
"2016 Q4", "2017 Q1", "2017 Q2", "2017 Q3", "2017 Q4"), class = "factor"),
`TRUE` = c(3, 0, 1, 0, 2, 1, 0, 1, 3, 0, 0, 0), `FALSE` = c(0,
0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0), OTHER = c(0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0)), class = c("data.table", "data.frame"
), row.names = c(NA, -12L), sorted = "QuarterAndYear")
我可以绘制这样的图表:
plot_ly(fullDT,x = ~QuarterAndYear,y=0,type = "scatter",mode = "lines")%>%add_trace(y = ~`TRUE`)%>%add_trace(y = ~`FALSE`)%>%add_trace(y = ~OTHER)%>%layout(xaxis= list(type = "category"))
这给了我几乎我需要的一切。也就是说,它给我第一列类别名称作为 x 轴的刻度标签。但是,"trace 0" 出现在图例中。如果我删除这个:
plot_ly(fullDT,type = "scatter",mode = "lines")%>%add_trace(y = ~`TRUE`)%>%add_trace(y = ~`FALSE`)%>%add_trace(y = ~OTHER)%>%layout(xaxis= list(type = "category"))
x 轴现在未标记。
我不确定如何让这两个同时工作。也许我可以施展某种传奇魔法?但我觉得有一种更清洁的方法。
我尝试了一些布局(xaxis = list(...))
无济于事...
画图的时候可以先空着,边画边加。当您绘制没有 y 的 x 时,它会添加 trace0
。所以画出你想要的图,然后使用 colNames
子集添加轨迹,从中删除你的 x,然后循环跟踪。
p <- plot_ly(type = 'scatter', mode = 'lines') %>%
layout(yaxis = list(title = "TRUE"))
colNames <- names(fullDT)
colNames <- colNames[-which(colNames == 'QuarterAndYear')]
for(trace in colNames){
p <- p %>% plotly::add_trace(data = fullDT, x = ~ QuarterAndYear, y = as.formula(paste0("~`", trace, "`")), name = trace)
print(paste0("~`", trace, "`"))
}
p
有了这个对象:
fullDT <-
structure(list(QuarterAndYear = structure(1:12, .Label = c("2015 Q1",
"2015 Q2", "2015 Q3", "2015 Q4", "2016 Q1", "2016 Q2", "2016 Q3",
"2016 Q4", "2017 Q1", "2017 Q2", "2017 Q3", "2017 Q4"), class = "factor"),
`TRUE` = c(3, 0, 1, 0, 2, 1, 0, 1, 3, 0, 0, 0), `FALSE` = c(0,
0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0), OTHER = c(0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0)), class = c("data.table", "data.frame"
), row.names = c(NA, -12L), sorted = "QuarterAndYear")
我可以绘制这样的图表:
plot_ly(fullDT,x = ~QuarterAndYear,y=0,type = "scatter",mode = "lines")%>%add_trace(y = ~`TRUE`)%>%add_trace(y = ~`FALSE`)%>%add_trace(y = ~OTHER)%>%layout(xaxis= list(type = "category"))
这给了我几乎我需要的一切。也就是说,它给我第一列类别名称作为 x 轴的刻度标签。但是,"trace 0" 出现在图例中。如果我删除这个:
plot_ly(fullDT,type = "scatter",mode = "lines")%>%add_trace(y = ~`TRUE`)%>%add_trace(y = ~`FALSE`)%>%add_trace(y = ~OTHER)%>%layout(xaxis= list(type = "category"))
x 轴现在未标记。 我不确定如何让这两个同时工作。也许我可以施展某种传奇魔法?但我觉得有一种更清洁的方法。
我尝试了一些布局(xaxis = list(...))
无济于事...
画图的时候可以先空着,边画边加。当您绘制没有 y 的 x 时,它会添加 trace0
。所以画出你想要的图,然后使用 colNames
子集添加轨迹,从中删除你的 x,然后循环跟踪。
p <- plot_ly(type = 'scatter', mode = 'lines') %>%
layout(yaxis = list(title = "TRUE"))
colNames <- names(fullDT)
colNames <- colNames[-which(colNames == 'QuarterAndYear')]
for(trace in colNames){
p <- p %>% plotly::add_trace(data = fullDT, x = ~ QuarterAndYear, y = as.formula(paste0("~`", trace, "`")), name = trace)
print(paste0("~`", trace, "`"))
}
p