GGplot pie chart error: Aesthetics must be either length 1 or the same as the data (98): y

GGplot pie chart error: Aesthetics must be either length 1 or the same as the data (98): y

我想使用 ggplot2 在 R 中创建饼图。我的代码是:

year.count <- c(24, 40, 30, 4)
prop.year <- year.count / sum(year.count) * 100
ypos.year <- cumsum(prop.year) - 0.5 * prop.year

ggplot(dat, aes(x = "", y = prop.year, fill = year)) +
  geom_bar(stat = "identity", width = 1, color = "white") +
  coord_polar("y", start = 0) +
  geom_text(aes(y = ypos.year, label = year), color = "white", size = 5)

代码引用自https://www.r-graph-gallery.com/piechart-ggplot2.html。 不幸的是,我总是收到一条错误消息:

Error: Aesthetics must be either length 1 or the same as the data (98): y

我应该怎么做才能解决这个问题?赞赏!

不清楚你想要什么。数据框 dat 未定义且 year 未唯一标识。这是一种可能的解释:

year.count <- c(24, 40, 30, 4)
prop.year <- year.count / sum(year.count) * 100
ypos.year <- cumsum(prop.year) - 0.5 * prop.year
dat <- data.frame("prop.year" = prop.year,
                  "ypos.year" = ypos.year,
                  "year.count" = year.count)
ggplot(dat, aes(x = ypos.year, y = prop.year, fill = year.count)) +
  geom_bar(stat = "identity", width = 1, color = "white") +
  coord_polar("y", start = 0) +
  geom_text(aes(y = ypos.year, label = year.count), color = "white", size = 5)