[英]Open Pie Chart/Donut Chart in R using Plotly with count and percentage
[英]Create plotly chart in R to toggle between count and percentage
总体思路是创建一个 plotly 图表,可以在显示计数和百分比之间切换。 我可以使用 updatemenu 更改显示的轨迹,并且轴刻度可以动态更改,但是当我在下面的示例中切换到“%”时,图例消失了。
我根本不是 plotly 专业人士,这就是我使用ggplotly()
的原因(我的真实示例更复杂,而ggplolty()
效果很好,)我想知道是否必须手动将图例添加到 % 跟踪(3?4)当第一条痕迹不可见时显示图例?
library(ggplot2)
library(plotly)
df <- structure(list(outcome = c("a", "b", "a", "b", "a", "b", "a",
"b", "a", "b"), n = c(59, 191, 28, 67, 29, 56, 33, 45, 32, 40
), pct = c(0.208480565371025, 0.674911660777385, 0.288659793814433,
0.690721649484536, 0.337209302325581, 0.651162790697674, 0.4125,
0.5625, 0.444444444444444, 0.555555555555556), day = c(1L, 1L,
2L, 2L, 3L, 3L, 4L, 4L, 5L, 5L)), class = "data.frame",
row.names = c(NA, -10L))
p <- ggplot(df, aes(day, n, color = outcome)) +
geom_line() +
geom_line(aes(y = pct))
ggplotly(p, dynamicTicks = TRUE) %>%
style(visible = FALSE, traces = 3:4) %>%
layout(
updatemenus = list(
list(
buttons = list(
list(args = list("visible", list(TRUE, TRUE, FALSE, FALSE)),
label = "n"),
list(args = list("visible", list(FALSE, FALSE, TRUE, TRUE)),
label = "%")
)
)
)
)
注意:这也发布在RStudio 社区上,但尚未收到任何答复。
@mfherman - 这是我想出的:
library(ggplot2)
library(plotly)
library(scales)
df <- structure(list(outcome = c("a", "b", "a", "b", "a", "b", "a",
"b", "a", "b"), n = c(59, 191, 28, 67, 29, 56, 33, 45, 32, 40
), pct = c(0.208480565371025, 0.674911660777385, 0.288659793814433,
0.690721649484536, 0.337209302325581, 0.651162790697674, 0.4125,
0.5625, 0.444444444444444, 0.555555555555556), day = c(1L, 1L,
2L, 2L, 3L, 3L, 4L, 4L, 5L, 5L)), class = "data.frame",
row.names = c(NA, -10L))
p <- ggplot(df, aes(day, n, color = outcome)) +
geom_line() +
geom_line(aes(y = pct)) +
theme(legend.position="bottom", legend.box = "horizontal")
chart_type <- list(
type = "buttons",
direction = "right",
xanchor = 'center',
yanchor = "top",
x = 0.5,
y = 1.27,
buttons = list(
list(
label = "nvals",
method = "update",
args = list( list("visible", list(TRUE, TRUE, FALSE, FALSE)),
list( yaxis = list( range = c(0,200) ,
ticksuffix = "") )
)),
list(
label = "%vals",
method = "update",
args = list( list("visible", list(FALSE, FALSE, TRUE, TRUE)),
list( yaxis = list( range = c(0,100) ,
ticksuffix = "%") )
))
))
# https://plotly.com/r/custom-buttons/#relayout-button
p2 <- ggplotly(p, dynamicTicks = TRUE, width = 640, height = 420) %>%
style(visible = FALSE, traces = 3:4) %>%
layout(
legend = list(orientation = "h",y = 0.8, x = 0.8),
updatemenus = list( chart_type )
)
for (i in 1:ncol(df)){
p2$x$data[[i]]$showlegend <- TRUE
}
p2
重要部分在底部 - > 看起来p2$x$data[[i]]$showlegend
值默认在第二个图表上设置为 false。 可能值得作为 github 项目的问题打开,以便将其作为选项添加到布局列表中。 看起来他们现在只有一个hide_legend
选项......很奇怪。
https://github.com/ropensci/plotly/issues
感谢这个问题帮助我解决这个问题:
https://github.com/ropensci/plotly/issues/842
编辑:根据评论中的要求添加了 % yaxis
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.