Search code examples
rggplot2pie-chart

Simple pie chart problem in ggplot2 and R


I'm trying to create a very simple pie chart using ggplot2. The proportions are incorrect as the data I have for three "type" categories is: "M-types" = 7, "N-types" = 151, "E-types" = 57 (see below for output of dput() to generate ).

N and Chronotype are my column headers as defined by colnames(). Here is the core of my code:

pie = ggplot(df, aes(x="", y=N, fill=Chronotype))+
  geom_bar(width = 1, stat = "identity")

pie = pie + 
  coord_polar("y", start=0)

Erroneous pie chart

Data from dput():

structure(list(N = structure(c(3L, 1L, 2L), .Label = c("151", 
    "57", "7"), class = "factor"), Chronotype = structure(c(2L, 3L, 
    1L), .Label = c("E-type", "M-type", "N-type"), class = "factor")), class = "data.frame", row.names = c(NA, 
    -3L))

Solution

  • Thanks to Jon, I just made the y data numeric:

    pie = ggplot(df, aes(x="", y=as.numeric(as.character(N)), fill=Chronotype))+
      geom_col() #(width = 1, stat = "identity")
    
    pie = pie + 
      coord_polar("y", start=0)
    
    pie