有人可以向我解释为什么我不能在此饼图中添加标签吗?
> 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
,将小值添加为geom_text_repel
,您将获得以下内容:
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))
编辑:将标签放置在饼图之外
如果您想将标签放置在饼图之外,则可以将它们的x值赋予以下属性:
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))
它回答了您的问题吗?