How to Put Labels Over Geom_Bar in R With Ggplot2

How to put labels over geom_bar in R with ggplot2

As with many tasks in ggplot, the general strategy is to put what you'd like to add to the plot into a data frame in a way such that the variables match up with the variables and aesthetics in your plot. So for example, you'd create a new data frame like this:

dfTab <- as.data.frame(table(df))
colnames(dfTab)[1] <- "x"
dfTab$lab <- as.character(100 * dfTab$Freq / sum(dfTab$Freq))

So that the x variable matches the corresponding variable in df, and so on. Then you simply include it using geom_text:

ggplot(df) + geom_bar(aes(x,fill=x)) + 
geom_text(data=dfTab,aes(x=x,y=Freq,label=lab),vjust=0) +
opts(axis.text.x=theme_blank(),axis.ticks=theme_blank(),
axis.title.x=theme_blank(),legend.title=theme_blank(),
axis.title.y=theme_blank())

This example will plot just the percentages, but you can paste together the counts as well via something like this:

dfTab$lab <- paste(dfTab$Freq,paste("(",dfTab$lab,"%)",sep=""),sep=" ")

Note that in the current version of ggplot2, opts is deprecated, so we would use theme and element_blank now.

How to put labels over geom_bar for each bar in R with ggplot2

Try this:

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
geom_bar(position = 'dodge', stat='identity') +
geom_text(aes(label=Number), position=position_dodge(width=0.9), vjust=-0.25)

ggplot output

Adding labels to individual % inside geom_bar() using R / ggplot2

Maybe there is a way to do this in ggplot directly but with some pre-processing in dplyr, you'll be able to achieve your desired output.

library(dplyr)
library(ggplot2)

data %>%
count(location, success) %>%
group_by(location) %>%
mutate(n = n/sum(n) * 100) %>%
ggplot() + aes(x = location, n, fill = success,label = paste0(round(n, 2), "%")) +
geom_bar(stat = "identity") +
geom_text(position=position_stack(vjust=0.5))

Sample Image

R ggplot2 geom_bar add labels with % sign

You had a typo in the geom_text aes (you forgot a paste0), which caused the % to be interpreted as the desired y-value. Adding a paste0() fixes it. I needed to do abs in order for the minus sign to disappear on the left-hand side.

# Plot
gg_pop_hisp = ggplot(pop_hisp_df, aes( x = forcats::as_factor(age_group), y = Value, fill = Type)) +
geom_bar(data = subset(pop_hisp_df, Type == "Females"), stat = "identity") +
geom_bar(data = subset(pop_hisp_df, Type == "Males"), stat = "identity") +
geom_text(aes(label = paste0(abs(Value), "%"))) +
scale_y_continuous(limits=c(-20,20),
breaks=c(-15,-10,0,10,15),
labels=paste0(c(15,10,0,10,15),"%")) + # CHANGE
scale_fill_manual(name = "", values = c("Females"="#FC921F", "Males"="#149ECE"), labels = c("Females", "Males")) +
ggtitle("HISPANIC POPULATION BY GENDER AND AGE GROUP") +
labs(x = "AGE GROUPS", y = "PERCENTAGE POPULATION", fill = "Gender") +
theme_minimal() +
theme(legend.position="bottom") +
coord_flip()

# Interactive
ggplotly(gg_pop_hisp) %>%
layout(
legend = list(
orientation = 'h', x = 0.3, y = -0.3,
title = list(text = '')
)
)

Sample Image

Can you put labels between horizontal bars?

Using facet:

#fix the order of factors
data3$System <- factor(data3$System, levels = c("Zivildienst", "Katastrophenschutz"))

#plot with facets
ggplot(data3, aes(x = System, y = Anzahl, fill = Einstellung)) +
geom_bar(stat = "identity") +
geom_text(aes(y = pos, label = label), size = 4) +
coord_flip() +
facet_wrap(vars(System), ncol = 1, scales = "free_y") +
scale_x_discrete(expand = c(0, 0)) + # make bar "fuller"
scale_y_continuous(expand = c(0, 0)) + # make bar "fuller"
scale_fill_manual(values = cbPalette) +
ggtitle("Werden Sie sich für die Alternative entscheiden?",
subtitle = "2000 Männer befragt") +
theme(panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.title.y = element_blank(),
aspect.ratio = .3,
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
strip.background = element_rect(fill = NA),# remove facet strip background
strip.text = element_text(hjust = 0) # left align the facet strip text
)

Sample Image

Labels geom_bar in ggplot R

As Roman Luštrik commented, the answer I was looking for is

ggplot(authors_interest_sex_count, aes(Country, freq, fill=Gender)) + 
geom_bar(stat="identity", position="dodge") +
geom_text(aes(label = freq), position=position_dodge(width=0.9), vjust=-1)

Sample Image
Thanks!

How to put geom_label in a geom_bar

We can calculate the labels that we want to display and use it in geom_label.

library(dplyr)
library(ggplot2)

c_clinicos %>%
group_by(Condición) %>%
mutate(label = sprintf('%d \n(%.2f %%)', Conteo, prop.table(Conteo) * 100),
label = replace(label, Conteo == 0, '')) %>%
ggplot() +
aes(x = Condición, fill = Estado, y = Conteo, label = label) +
geom_col() +
scale_fill_manual(values = list(
Ausente = "#FF1100", Presente = "#538FF6")) +
labs(x = "Condición clínica", y = "Nº Personas. ",
title = "Distribución de la presencia por enfermedad",
subtitle = "Muestra de 810 pacientes", fill = "Estado:") +
geom_label(position=position_stack(vjust=0.5), color = 'white') +
coord_flip() +
theme_linedraw()

Sample Image



Related Topics



Leave a reply



Submit