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

J.S*_*ree 1 charts r count donut-chart plotly

我正在尝试使用 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"))
Run Code Online (Sandbox Code Playgroud)

此图表最终会出现在 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))
Run Code Online (Sandbox Code Playgroud)

此外,如果您可以展示如何按部门对它进行 facet_wrap,那将非常有帮助。我一直让它说NULL!

谢谢!

Max*_*ers 5

如果您想在饼图/甜甜圈图的中心添加文本,您可以添加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))
Run Code Online (Sandbox Code Playgroud)

为了更改饼图每个段中显示的标签,您可以使用text.

p <- plot_ly(values, labels = ~status, values = ~count, text = ~count)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

完整代码

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
Run Code Online (Sandbox Code Playgroud)