Reputation: 617
How can I add the percentage above the bars from a data.frame?
How could I use two decimal places after the comma.
I tried to apply ggplot, but I couldn't get it wrong:
a <- c("até 50","50-150","150-500","500-2000")
b <- c(107,38,14,3)
pcent <- c(66.049383, 23.456790, 8.641975, 1.851852)
df <- data.frame(a,b,pcent)
ggplot(df, aes (x=reorder(a, -b), y=b, label=pcent)) +
geom_col(fill="#70A2E7") +
labs(x = "Faixa de desmatamento (ha)", y="Quantidade de polígonos de desmatamento", title = "Distribuição dos polígonos de desmatamento") +
geom_text(aes(y = pcent, label = scales::percent(pcent)), vjust = -0.2)+
scale_y_continuous(labels = scales::percent)
Upvotes: 1
Views: 82
Reputation: 388907
Your y-axis is raw count and you want to plot percentage on top of bars which can be bit misleading. Anyway, you can do :
library(ggplot2)
ggplot(df, aes (x=reorder(a, -b), y=b, label=pcent)) +
geom_col(fill="#70A2E7") +
labs(x = "Faixa de desmatamento (ha)",
y="Quantidade de polígonos de desmatamento",
title = "Distribuição dos polígonos de desmatamento") +
geom_text(aes(label = paste0(round(pcent,2), '%')), vjust = -0.5)
Or probably better to show percentages on y-axis.
ggplot(df, aes (x=reorder(a, -b), y=pcent, label=pcent)) +
geom_col(fill="#70A2E7") +
labs(x = "Faixa de desmatamento (ha)",
y="Quantidade de polígonos de desmatamento",
title = "Distribuição dos polígonos de desmatamento") +
geom_text(aes(label = paste0(round(pcent,2), '%')), vjust = -0.5) +
scale_y_continuous(labels = function(x) paste0(x, '%'))
Upvotes: 1