Search code examples
rpie-chart

pie chart problem involving positive values


I am trying to create a pie chart. Here is some data:

tst1  tst2 tst34
13.3  2.3  0.0
70.2  4.5  1.2
1.3   5.2  3.3

I tried this code:

df_pie <- df %>% select("tst1", "tst2", "tst34")
df_pie$tst1 <- as.numeric(df_pie$tst1)
df_pie$tst2 <- as.numeric(df_pie$tst2)
df_pie$tst34 <- as.numeric(df_pie$tst34)
lbls <- c("Stage 1", "Stage 2", "Stage 3")
pie(df_pie, labels = lbls, main="Pie Chart")

But, I am getting an error message in R which is below:

Error in pie(df, labels = lbls, main = "Percent of Time in Each Sleep Stage") : 
  'x' values must be positive.

I have read some articles where people have had this issue before. I have checked that the data are positive and numeric. Can someone please help?


Solution

  • The x in pie takes only a positive vector as input and not a data.frame. According to ?pie

    x - a vector of non-negative numerical quantities. The values in x are displayed as the areas of pie slices.

    Here is an option with pmap to loop over each row

    library(purrr)
    par(mfrow = c(2, 2))
    
    lst1 <- pmap(df_pie, ~ pie(c(...), labels = lbls, 
           main = 'Percent of Time in each Sleep Stage'))
    

    -output

    enter image description here


    If it would be the average of each column, then use colMeans

    pie(colMeans(df_pie), labels = lbls, 
               main = 'Percent of Time in each Sleep Stage')
    

    -output

    enter image description here


    Or with apply

    par(mfrow = c(2, 2))
    lst1 <- apply(df_pie, 1, function(x) pie(x, labels = lbls, 
             main = 'Percent of Time in each Sleep Stage'))
    

    data

    df_pie <- structure(list(tst1 = c(13.3, 70.2, 1.3), tst2 = c(2.3, 4.5, 
    5.2), tst34 = c(0, 1.2, 3.3)), class = "data.frame", row.names = c(NA, 
    -3L))