[英]Open Pie Chart/Donut Chart in R using Plotly with count and percentage
我正在尝试使用plotly在R中制作一个甜甜圈图。 我尝试了ggplot,但无法满足我的需要。 这是一个示例数据集:
library(dplyr)
testfile <- tibble(personID = 1:10,
status = c("bad", "good", "bad", "bad", "bad", "bad", "bad", "bad", "bad", "good"),
department = c("sales", "sales", "marketing", "sales", "marketing", "management", "management", "sales", "sales", "sales"))
该图表最终将在PowerPoint中显示,因此不需要响应。 取而代之的是,我需要饼状图说出不属于每种状态和计数的百分比,而不是对其进行滚动。 另外,在饼图的中心,我想说“好”类别中的百分比。
这是我到目前为止的代码。 它具有可见的百分比,但不滚动,但没有计数,并且中心没有百分比。
library(plotly)
p <- testfile %>%
group_by(status) %>%
summarize(count = n()) %>%
plot_ly(labels = ~status, values = ~count) %>%
add_pie(hole = 0.6) %>%
layout(title = "Ratio of Good to Bad", showlegend = F,
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = TRUE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = TRUE))
另外,如果您可以显示如何按部门进行facet_wrap处理,那将非常有帮助。 我一直说它为NULL!
谢谢!
如果您想在饼图/甜甜圈图的中央添加文本,可以添加注释 。
values <- testfile %>%
group_by(status) %>%
summarize(count = n())
good <- values %>% filter(status == 'good')
p <- layout(p, annotations=list(text=paste(good$count / sum(values$count) * 100, "%", sep=""), "showarrow"=F))
为了更改在饼图的每个部分中显示的标签,可以使用text
。
p <- plot_ly(values, labels = ~status, values = ~count, text = ~count)
完整的代码
library(dplyr)
library(plotly)
testfile <- tibble(personID = 1:10,
status = c("bad", "good", "bad", "bad", "bad", "bad", "bad", "bad", "bad", "good"),
department = c("sales", "sales", "marketing", "sales", "marketing", "management", "management", "sales", "sales", "sales"))
values <- testfile %>%
group_by(status) %>%
summarize(count = n())
good <- values %>% filter(status == 'good')
p <- plot_ly(values, labels = ~status, values = ~count, text = ~count) %>%
add_pie(hole = 0.6) %>%
layout(title = "Ratio of Good to Bad", showlegend = F,
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = TRUE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = TRUE))
p <- layout(p, annotations=list(text=paste(good$count / sum(values$count) * 100, "%", sep=""), "showarrow"=F))
p
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.