1

I was trying to plot a pie char using ggplot2. The code is pasted as following

df <- data.frame(
  category = LETTERS[1 : 14],
  count = c(86, 2, 6, 315, 98, 140, 48, 167, 226, 269, 2, 70, 3, 112)
)

ggplot(df,
       aes(x = "", y = count, fill = category)) +
  geom_bar(stat = "identity", width = 1) +
  geom_text(aes(label = count), 
            position = position_stack(vjust = 0.5)) +
  coord_polar("y", start = 0)

And the output is shown as the following picture:

enter image description here

May I know how to set the labels to avoid overlapping? Thank you :)

2
  • The best way is not to use a pie chart. There are other options including a simple table of values. It is difficult to get a sense of scale from the pie wedges. Commented Jun 18, 2024 at 0:13
  • For small wedges, you could consider combining them into an "other" category as in this thread: stackoverflow.com/questions/78444478/… Commented Jun 18, 2024 at 3:07

1 Answer 1

1

Try the following, I have been using this method in some older versions

# Install ggrepel 
install.packages("ggrepel")

# Load the library
library(ggplot2)
library(ggrepel)

# Create the data frame
df <- data.frame(
  category = LETTERS[1:14],
  count = c(86, 2, 6, 315, 98, 140, 48, 167, 226, 269, 2, 70, 3, 112)
)

# Plot the pie chart with non-overlapping labels
ggplot(df, aes(x = "", y = count, fill = category)) +
  geom_bar(stat = "identity", width = 1) +
  coord_polar("y", start = 0) +
  geom_text_repel(aes(label = count),
                  position = position_stack(vjust = 0.5),
                  box.padding = 0.5,
                  point.padding = 0.5,
                  segment.color = 'grey50') +
  theme_void()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.