Home > Net >  Can't draw a concentric pie chart in R
Can't draw a concentric pie chart in R

Time:05-26

I have the following data:

Phyla       V4         Fl
 <chr>     <dbl>      <dbl>

Proteobacteria  88.58    81.43  
Firmicutes  7.33    15.34   
Actinobacteriota    1.55    1.94        
Bacteroidota    2.20    1.25    

I want to display the data using a concentric pie chart. I have a couple of trials:

mycols <- c("#eee0b1", "#da8a67", "#e63e62", "#0033aa")
ggplot(df, aes(x = 2, y = V4, fill = Phyla))  
  geom_bar(stat = "identity", color = "white")  
  coord_polar(theta = "y", start = 0) 
  geom_text(aes(y = Fl, label = V4), color = "white") 
  scale_y_continuous(breaks=min(df$Fl):max(df$Fl))  
  scale_fill_manual(values = mycols)  
  theme_void() 
  xlim(0.5, 2.5)

This generates enter image description here

So, I got only one column displayed.

The other trial used this:

pie(x=c(88.58,7.33,1.55,2.2),labels="",
col=c("#eee0b1", "#da8a67", "#e63e62", "#0033aa"))
par(new=TRUE)
pie(x=c(81.43,15.34,1.94, 1.25),labels=c("Proteobacteria","Firmicutes","Actinobacteriota", "Bacteroidota"),radius=.5,
    col=c("#eee0b1", "#da8a67", "#e63e62", "#0033aa"))

that generates this figure: enter image description here

I do not know which is easier to fix to generate the concentric pie. I need to include the color legend and label each pie with the category name (V4, Fl) along with adding the values as percentages.

CodePudding user response:

You may try this

df %>%
    pivot_longer(-Phyla, names_to = "type", values_to = "y") %>%
    ggplot(aes(x = type, y = y))  
    geom_bar(aes(fill = Phyla), stat = "identity",
      color = "white", position = "fill", width=0.7)  
    coord_polar(theta = "y", start = pi/2)  
    geom_text(aes(y = y, group = Phyla, label = y),
      color = "white", position = position_fill(vjust=0.5))  
    geom_text(aes(x = x, y = y, label = type),
      data = data.frame(x = c(2.5, 3.5), y = c(0, 0), type = c("V4", "Fl"))
    )  
    scale_fill_manual(values = mycols)  
    scale_x_discrete(limits = c(NA, "V4", "Fl"))  
    theme_void()
  • pivot_longer transforms your data from "wide" to "long", so that you can draw multiple columns.
  • position="fill" in geom_bar() and position_fill in geom_text() will scale y value into [0,1], so that two columns are aligned.
  • vjust=0.5 in position_fill will display values to their corresponding areas.
  • It is a little difficult to label the circle directly using x axis texts, but you can label them manually using geom_text() with a new data.frame(x=c(2.5,3.5),y=c(0,0),type=c("V4","Fl"))

result

  • Related