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