简体   繁体   中英

Cannot add labels to piechart with R ggplot2

can somebody explain to me why i can't add labels to this pie chart?

> 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"
))

this is the code im using for the plot:

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")

Thanks in advance

With polar coordinates, you need to define some position for your labels. Here, we can define these position as this:

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 

Then, you can add this label to your plot. However, as you have very close values (0 and 0.88%), those will probably overlap. So, you could use geom_text_repel instead but it will also change the position of other labels. So, I decided to add big values as regular geom_text and small values with geom_text_repel and you get the following:

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))

在此处输入图片说明


EDIT: Placing labels outside of the pie chart

If you want to place your labels outside of the pie chart, you can attribute them ax value as follow:

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))

在此处输入图片说明

Does it answer your question ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM