[英]Cannot add labels to piechart with R ggplot2
有人可以向我解釋為什么我不能在這個餅圖中添加標簽嗎?
> dput (test)
structure(list(Status = c("Isolamento domiciliare", "Ricoverati con sintomi",
"Terapia intensiva", "Deceduti", "Dimessi guariti"), label = c("69.03%",
"17.70%", "12.39%", "0.88%", "0.00%"), value = c(78, 20, 14,
1, 0)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"
))
這是我用於繪圖的代碼:
ggplot(test, aes(x="", y=value, fill=Status)) +
geom_bar(stat="identity", width=1, color="white") +
coord_polar("y", start=0) +
theme_void()+ labs(fill = "Situazione attuale")
提前致謝
使用極坐標,您需要為標簽定義一些位置。 在這里,我們可以將這些位置定義為:
library(dplyr)
test2 <- test %>%
arrange(desc(Status)) %>%
mutate(percent = value / sum(value)*100) %>%
mutate(ypos = cumsum(percent)-0.5*percent)
# A tibble: 5 x 5
Status label value percent ypos
<chr> <chr> <dbl> <dbl> <dbl>
1 Terapia intensiva 12.39% 14 12.4 6.19
2 Ricoverati con sintomi 17.70% 20 17.7 21.2
3 Isolamento domiciliare 69.03% 78 69.0 64.6
4 Dimessi guariti 0.00% 0 0 99.1
5 Deceduti 0.88% 1 0.885 99.6
然后,您可以將此標簽添加到您的繪圖中。 但是,由於您的值非常接近(0 和 0.88%),因此它們可能會重疊。 因此,您可以使用geom_text_repel
代替,但它也會更改其他標簽的位置。 因此,我決定使用geom_text_repel
添加大值作為常規geom_text
和小值,您會得到以下內容:
library(ggrepel)
library(ggplot2)
ggplot(test2,aes(x="", y=percent, fill=Status)) +
geom_bar(stat="identity", width=1, color="white") +
coord_polar("y", start=0) +
theme_void()+ labs(fill = "Situazione attuale")+
geom_text(data = subset(test2, value >2), aes(label = label, y = ypos))+
geom_text_repel(data = subset(test2, value <2), aes(label = label, y = ypos))
編輯:將標簽放置在餅圖之外
如果你想把你的標簽放在餅圖之外,你可以將它們的 ax 值歸為如下:
ggplot(test2,aes(x=1, y=percent, fill=Status)) +
geom_bar(stat="identity", width=1, color="white") +
coord_polar("y", start=0) +
theme_void()+ labs(fill = "Situazione attuale")+
geom_text(data = subset(test2, value >2), aes(label = label, y = ypos, color = Status), show.legend = FALSE, x= 1.75)+
geom_text_repel(data = subset(test2, value <2), aes(label = label, y = ypos, color = Status), x = 1.75, show.legend = FALSE)+
expand_limits(x = c(1,1.8))
它回答你的問題嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.