I am plotting my data and want to display totals on top of each bar but as soon as I add total count the bars disappear.
long<- data.frame(
Name = c("abc","abc","abc","gif","gif","gif","xyz","xyz","xyz"),
variable = c("a","b","c","a","b","c","c","b","a"),
value = c(4,6,NA,2,8,1,6,NA,NA))
Code
p<-long %>%
ggplot() aes(Name, value, fill=variable)
geom_bar(stat="summary", position = "fill")
scale_y_continuous(labels = scales::percent_format())
ylab("Total_num")
ggtitle("Totalnum")
theme(plot.title = element_text(size = 20, hjust = 0.5))
theme(axis.text.x = element_text(angle = 75, vjust = 0.95, hjust=1))
p stat_summary(fun.y = sum, aes(label = ..y.., group = Name)
geom_text(stat='value', aes(group=Name, label=.."value"..), position = position_stack(vjust = 0.5))
CodePudding user response:
You can achieve that creating another df with the sum of value per Name and passing this to geom_text()
long<- data.frame(
Name = c("abc","abc","abc","gif","gif","gif","xyz","xyz","xyz"),
variable = c("a","b","c","a","b","c","c","b","a"),
value = c(4,6,NA,2,8,1,6,NA,NA))
long_totals <- long %>%
group_by(Name) %>%
summarise(Total = sum(value, na.rm = T))
p <- ggplot()
geom_bar(data = long,
aes(x = Name,
y = value,
fill=variable),
stat="summary",
position = "fill")
geom_text(data = long_totals,
aes(y = 100,
x = Name,
label = Total),
size = 7,
position = position_fill(vjust = 1.02))
scale_y_continuous(labels = scales::percent_format())
ylab("Total_num")
ggtitle("Totalnum")
theme(plot.title = element_text(size = 20, hjust = 0.5))
theme(axis.text.x = element_text(angle = 75, vjust = 0.95, hjust=1))