Reputation: 407
I have developed a ggplot graph but now I am trying to add calculated label which shows increase in % year-on-year?
My data frame is very simple (result of aggregate from the main dataset)
'data.frame': 4 obs. of 3 variables:
$ Year : int 2011 2012 2013 2014
$ TotalPay: num 71744 74113 77611 75466
I have a code for my graph:
library(ggplot2)
ggplot(d1, aes(x=Year, y=TotalPay)) + geom_bar(stat="identity") +
labs(x="Year", y="Average Total Pay ($)")
and now trying to use stat_bin for lables? The calculation is Actual Year - Previous Year * 100%. I have this but not sure how to fill percent ()
stat_bin(aes (labels = paste("Total Pay" = ,scales::percent(())), vjust = 1, geom = "TexT")
Upvotes: 4
Views: 1412
Reputation: 19857
I would compute the change beforehand and then plot it with geom_text
:
library(dplyr)
d1 <- data.frame(Year=2011:2014,TotalPay=c(71744,74112,77611,65466))
d1 <- mutate(d1,change=(TotalPay - lag(TotalPay))/lag(TotalPay))
ggplot(d1, aes(x=Year, y=TotalPay)) + geom_bar(stat="identity") +
labs(x="Year", y="Average Total Pay ($)") +
geom_text(data=d1[-1,],aes(label = scales::percent(change)), vjust = 1)
Upvotes: 6