使用带有计数和百分比的Plotly在R中打开饼图/甜甜圈图

时间:2019-06-10 17:21:41

标签: r charts count plotly donut-chart

我正在尝试使用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!

谢谢!

1 个答案:

答案 0 :(得分:1)

如果您想在饼图/甜甜圈图的中央添加文本,可以添加annotation

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)

enter image description here

完整代码

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