pavan
pavan

Reputation: 21

ggplot Donut chart is not as desired

I am trying to create a donut chart using ggplot2 with the following data (example).

    library(ggplot2)
    library(svglite)
    library(scales)

    # dataframe
    Sex = c('Male', 'Female')
    Number = c(125, 375)
    df = data.frame(Sex, Number)
    df

The code I used to generate donut chart is

    ggplot(aes(x= Sex, y = Number, fill = Sex), data = df) +
    geom_bar(stat = "identity") +
    coord_polar("y") +
    theme_void() +
    theme (legend.position="top") + # legend position
    geom_text(aes(label = percent(Number/sum(Number))), position = position_stack(vjust = 0.75), size = 3) +
    ggtitle("Participants by Sex")

The above code generated the following chart. Some how not convinced with the chart.

enter image description here

For our purposes, the following chart would better communicate the message. How do I create a chart like this. Where am I doing wrong in my code? I have googled with out any success. Thanks in advance for help. enter image description here

Upvotes: 0

Views: 1326

Answers (1)

Jack Brookes
Jack Brookes

Reputation: 3830

They aren't in the same 'circle' because they have different x values. Imagine it as a normal plot first (i.e. without coord_polar("y")) and this will become clear. What you really want is them set at the same x value and then stacked. Here I set x to 2 because it then makes a nicely sized "donut".

donut <- ggplot(df, aes(x = 2, y = Number, fill = Sex)) +
  geom_col(position = "stack", width = 1) +
  geom_text(aes(label = percent(Number/sum(Number))), position = position_stack(vjust = 0.75), size = 3) +
  xlim(0.5, 2.5) +
  ggtitle("Participants by Sex")

donut

enter image description here

donut +
  coord_polar("y") +
  theme_void() +
  theme(legend.position="top")

enter image description here

Upvotes: 3

Related Questions