简体   繁体   中英

R ggplot2: Plot percentage values on top of Bar chart with proportion calculated within the geom_bar function

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:

在此处输入图片说明

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM