In ggplot2, how to add a white hole in the middle of the pie chart
Asked Answered
F

2

5

In ggplot2, how to add a white hole in the middle of the pie chart? Please refer to below code for current plot (the left plot) . Thanks!

library(tidyverse)
pie_data <- data.frame(category=c('A','B','C','A','B','C'),
                       year=c(2020,2020,2020,2021,2021,2021),
                       sales=c(40,30,20,10,15,10))




pie_data %>% ggplot(aes(x=factor(year),y=sales,fill=category))+
  geom_col(position='fill',width=1,color='white')+
 coord_polar(theta = 'y')+
  theme_void()

enter image description here

Forficate answered 8/2, 2022 at 11:24 Comment(1)
https://mcmap.net/q/412768/-ggplot-donut-chart linking because an important thread regarding donut chart, for the interestedPresumable
P
8

Just widen the limits of your x axis (it's easier to do this if you don't convert the year into a factor):

pie_data %>% ggplot(aes(x = year, y = sales, fill = category))+
  geom_col(position = 'fill', width = 1, color = 'white') +
  coord_polar(theta = 'y') + 
  lims(x = c(2019, 2022)) +
  theme_void()

enter image description here

You can control the size of the white hole by changing 2019 in the above code. The earlier the year, the larger the hole:

pie_data %>% ggplot(aes(x = year, y = sales, fill = category))+
  geom_col(position = 'fill', width = 1, color = 'white') +
  coord_polar(theta = 'y') + 
  lims(x = c(2017, 2022)) +
  theme_void()

enter image description here

Prepense answered 8/2, 2022 at 11:32 Comment(1)
@Forficate that's down to the plotting device. If you are using RStudio, in the menu bar, go to Tools -> Global Options -> General -> Graphics and select "AGG" for graphics backendPrepense
K
2

You can add an hollow bar at the center:

  pie_data %>% ggplot(aes(x=factor(year),y=sales,fill=category))+
      geom_col(position='fill',width=1,color='white')+
      coord_polar(theta = 'y')+
      geom_col(aes(x=0,y=0))+
      theme_void()

enter image description here

if you want a larger circle, use a negative x coordinate:

geom_col(aes(x=-1,y=0))

enter image description here

Kronstadt answered 8/2, 2022 at 12:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.