I want to create a pie chart in R using ggplot2. My codes are:
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)
The codes were referenced from https://www.r-graph-gallery.com/piechart-ggplot2.html. Unfortunately, I always got an error message:
Error: Aesthetics must be either length 1 or the same as the data (98): y
What should I do to fix the problem? Appreciated!
It's not clear what you want. The data frame dat
is not defined and year
is not uniquely identified. Here's one possible interpretation:
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)