Search code examples
rggplot2pie-chart

Pie Chart in ggplot2 picking single samples from a dataframe


I would like to produce a simple pie chart from my dataframe, which has multiple samples.

A sample dataframe looks like this:

Sample <- c("S1", "S2", "S3")
Var1 <- c(4,5,3)
Var2 <- c(1,9,4)
Var3 <- c(2,1,3)
df <- data.frame(Sample, Var1, Var2, Var3)

I would like to plot a pie chart for each sample. In excel, this is pretty easy and straight forward and looks like the following.

Excel Example

How can I produce something similar using ggplot2?


Solution

  • Your data just seems to be in a non-tidy format. It's easier to plot it if you reshape it. Here's an example using tidyr

    library(ggplot2)
    library(tidyr)
    df %>% 
      pivot_longer(-Sample) %>% 
      ggplot() + 
        aes(x="", y=value, fill=name) + 
        geom_col(position="fill") + 
        facet_wrap(~Sample) + 
        coord_polar("y")