0

I have this code:

as_tibble(earlyCiliated[[]]) %>% 
  ggplot(aes(x="", y=Phase, fill=Phase)) + geom_col() +
  coord_polar("y", start=0)  + 
  geom_text(aes(label = paste0(Phase, "%")))

and my output looks like this: PieChart

What am I doing wrong that's causing the labels to all be on top of each other?

  • 4
    It's easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. – MrFlick Aug 12 '22 at 13:56
  • 2
    Does this answer your question? [how to adjust text location in a pie chart / with polar coordinates](https://stackoverflow.com/questions/66777677/how-to-adjust-text-location-in-a-pie-chart-with-polar-coordinates) – Basti Aug 12 '22 at 13:57
  • Or see this question as well: https://stackoverflow.com/questions/71100718/add-labels-to-pie-chart-ggplot2-after-specifying-factor-orders. You need to calculate the values where you want the labels to go. ggplot doesn't guess correctly by default. – MrFlick Aug 12 '22 at 13:58

1 Answers1

0

I can't completely recreate your plot because I do not have your data. That being said, you can try this:

install.packages("ggrepel")
library(ggrepel)

as_tibble(earlyCiliated[[]]) %>% 
    ggplot(aes(x="", y=Phase, fill=Phase)) + geom_col() +
    coord_polar("y", start=0)  + 
    geom_label_repel(data = earlyCiliated[[]],
                     aes(y = Phase, label = paste0(Phase, "%")),
                     size = 4.5, nudge_x = 1, show.legend = FALSE)

This is what it will look like (using other data because none was provided)

library(ggplot2)
library(ggrepel)
library(tidyverse)

df <- data.frame(value = c(15, 25, 32, 28),
                 group = paste0("G", 1:4))

# Get the positions
df2 <- df %>% 
  mutate(csum = rev(cumsum(rev(value))), 
         pos = value/2 + lead(csum, 1),
         pos = if_else(is.na(pos), value/2, pos))

ggplot(df, aes(x = "" , y = value, fill = fct_inorder(group))) +
  geom_col(width = 1, color = 1) +
  coord_polar(theta = "y") +
  scale_fill_brewer(palette = "Pastel1") +
  geom_label_repel(data = df2,
                   aes(y = pos, label = paste0(value, "%")),
                   size = 4.5, nudge_x = 1, show.legend = FALSE) +
  guides(fill = guide_legend(title = "Group")) +
  theme_void()

Pie Chart

amanwebb
  • 380
  • 2
  • 9