-1

I'm just beggining with programming. I have this data frame:

data1 = data.frame(NSE=c("A-B", "C", "D-E"), Percentage=c(68, 66, 63))

And I made this barplot:

a = ggplot(data1, aes(x=NSE, y=Percentage))+
geom_bar(stat = "identity", width=0.6, fill = "red", color = "grey40", alpha = 5)+ 
geom_text(aes(label=Percentage), vjust=1.5, color="white", 
size=3)+
ggtitle("No se sintieron discriminados en los últimos 
doce meses, según NSE (en porcentaje)")+labs(y="", x="")+
theme(plot.title = element_text(color="black", size=10, face="bold"))+ylim(0,100)

It creates three bars corresponding to values 68, 66 and 63. But I want the bars to show these values as percentages (68%, 66%, 63%). What should I do to get the that?

Thank you in advance.

  • 1
    Does this answer your question? [Show % instead of counts in charts of categorical variables](https://stackoverflow.com/questions/3695497/show-instead-of-counts-in-charts-of-categorical-variables) – tjebo Aug 02 '20 at 10:50

2 Answers2

1

Using scales::percent and scales::percent_format this could be achieved like so:

library(ggplot2)
library(scales)

data1 = data.frame(NSE=c("A-B", "C", "D-E"), Percentage=c(68, 66, 63))

ggplot(data1, aes(x=NSE, y=Percentage))+
  geom_bar(stat = "identity", width=0.6, fill = "red", color = "grey40", alpha = 5)+ 
  geom_text(aes(label=scales::percent(Percentage, scale = 1, accuracy = 1)), vjust=1.5, color="white", 
            size=3)+
  scale_y_continuous(labels = scales::percent_format(scale = 1, accuracy = 1), limits = c(0,100)) +
  ggtitle("No se sintieron discriminados en los ultimos 
doce meses, segun NSE (en porcentaje)")+labs(y="", x="")+
  theme(plot.title = element_text(color="black", size=10, face="bold"))

Created on 2020-08-02 by the reprex package (v0.3.0)

stefan
  • 90,330
  • 6
  • 25
  • 51
0

Without using the scales package one could simply use

function(x) paste0(round(x*100), "%)

in the label aesthetic of geom_text, as follows:

+ geom_text(aes(label=paste0(round(Percentage), "%")), vjust=1.5, color="white", 
size=3)

Additionally, in the labels argument of scale_y_continuous one could do the same, like so

+ scale_y_continuous(labels = function(x) paste0(round(x), "%"))
o_v
  • 112
  • 8