我想使用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)