R ggplot2: Plot percentage values on top of Bar ch

2019-08-23 11:28发布

问题:

Data used :

structure(list(Year = c(2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 
2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 
2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 
2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 
2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 
2014L, 2014L, 2014L, 2014L, 2014L), Rating = c(4L, 4L, 4L, 3L, 
4L, 4L, 4L, 3L, 4L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 
5L, 5L, 5L, 5L, 5L, 5L, 5L, 4L, 5L, 5L, 5L, 5L, 4L, 4L, 4L, 5L, 
5L, 4L, 5L, 5L, 5L, 5L, 4L, 4L, 4L, 5L, 5L)), .Names = c("Year", 
"Rating"), class = "data.frame", row.names = c(NA, -47L))

Below is the code I have used to plot the bar chart :

ggplot(subset(ws_inf, ws_inf$Year=="2014"), mapping = aes(x=Rating)) +
  geom_bar(mapping = aes(y = ..prop.., group = 1)) + 
  ggtitle("2014") +
  ylab("Percentage") + 
  xlab("Rating")

I have taken the proportions in the geom_bar function itself. I wanted to know how can I display the respective percentage values on top of the bar. The bar chart looks like

I did search on stack overflow but most of them had percentages already calculated. I wanted to know if in my way if I can plot the percentage values.

I tried this

ggplot(subset(ws_inf, ws_inf$Year=="2014"), mapping = aes(x=Rating)) +
  geom_bar(mapping = aes(y = (..prop..)*100, group = 1)) +
  geom_text(stat='count', aes(label=round((..prop..)*100,2)), vjust=-0.5) + 
  ggtitle("2014") +
  ylab("Percentage") + 
  xlab("Rating")

Got the below graph , but is there a way to adjust the text:

回答1:

Use vjust. How about:

 library(ggplot2)
   ggplot(subset(ws_inf,ws_inf$Year=="2014"), mapping = aes(x=Rating)) +
     geom_bar(aes(y = ..prop.., group = 1)) +
     geom_text(aes( y = ..prop.., label = scales::percent(..prop..)), stat = "count", vjust = -1)