[英]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.