I want to add percent value to this chart to this data frame
s<-# Basic piechart
ggplot(heart, aes(x="", y="", fill=sex)) +
geom_bar(stat="identity", width=1) +
coord_polar("y", start=0)
plot(s)
I want to add percent value to this chart to this data frame
s<-# Basic piechart
ggplot(heart, aes(x="", y="", fill=sex)) +
geom_bar(stat="identity", width=1) +
coord_polar("y", start=0)
plot(s)
You haven't shared your data, but your plot code implies that heart
is a data frame that includes a column labeled sex
which is either of factor or character class, so this toy data set should suffice to demonstrate.
set.seed(1)
heart <- data.frame(sex = sample(c("Male", "Female"), 24, TRUE))
Your plotting code is actually stacking all the males, then all the females, without counting them, so there is no way for the geom_text
to know where in this stack it should be plotting. Instead, you need to use the default stat of geom_bar
, which is stat = "count"
, then plot the geom_text
at the appropriate points:
library(ggplot2)
ggplot(heart, aes(x = "", fill = sex)) +
geom_bar(width = 1) +
geom_text(data = as.data.frame(table(heart$sex)),
aes(group = Var1, label = scales::percent(Freq / sum(Freq)),
y = Freq, fill = Var1),
position = position_stack(vjust = 0.5)) +
coord_polar("y", start = 0) +
theme_void()
#> Warning: Ignoring unknown aesthetics: fill
Created on 2020-11-19 by the reprex package (v0.3.0)