涉及正值的饼图问题

pie chart problem involving positive values

我正在尝试创建饼图。这是一些数据:

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

我试过这段代码:

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")

但是,我在 R 中收到如下错误消息:

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

我读过一些以前有人遇到过这个问题的文章。我检查过数据是正数和数字。有人可以帮忙吗?

pie 中的 x 只接受正数 vector 作为输入,而不是 data.frame。根据?pie

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

这里有一个选项 pmap 可以遍历每一行

library(purrr)
par(mfrow = c(2, 2))

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

-输出


如果是每列的平均值,则使用colMeans

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

-输出


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'))

数据

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))