I'm trying to add sample sizes to the top of my bar charts in ggplot2, but haven't been able to figure out how. I'd like them to read as, for example, n=15. Any ideas before I retreat to Photoshop? Here's my code, data and one of the graphs I'd like to label:
#Load packages
library(ggplot2)
library(readxl)
library('showtext')
#Import data
breadth <- read_excel([Insert file path here])
View(breadth)
#Define scale_fill_manual
cbPalette <- c("#b9503d",
"#43c9b0")
#Define font
font_add(family = "Arial", regular = "Arial.ttf")
#Enable font
showtext_auto()
ggplot(breadth, aes(fill=breadth, y=count, x=category)) +
geom_bar(position='stack', stat='identity') +
labs(fill='Habitat breadth', x='', y='Number of species') +
scale_fill_manual(values=cbPalette) +
theme_classic() +
theme(axis.text.x = element_text(size = 13), axis.title.y = element_text(size = 12)) +
theme(text = element_text(family = "Arial")) +
theme(axis.title.y = element_text(margin = margin(t = 0, r = 10, b = 0, l = 0))) +
scale_x_discrete(labels=c('Non-cacher', 'Generalist cacher', 'Specialist cacher'))
Here's my dput(breadth)
output:
structure(list(breadth = c("Habitat specialist", "Habitat specialist",
"Habitat specialist", "Habitat generalist", "Habitat generalist",
"Habitat generalist"), category = c("Non-cacher", "Non-specialised cachers",
"Specialised cachers", "Non-cacher", "Non-specialised cachers",
"Specialised cachers"), count = c(0, 2, 10, 3, 30, 10)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -6L))
I've tried using the geom_text
function, but I was only able to add the sample sizes to each division.