TomG888
TomG888

Reputation: 9

How to label a bar chart in ggplot2

I'm trying to make a very simple bar chart (screenshot).

I have two questions:

First, how can I label the bars? I've managed to label one stack correctly, but I don't know how I label the other one without changing them both. I want shaded be labelled with 76 and exposed with 277?

Second, how do I change the colour of the columns, say I wanted red and blue for example?

Thanks

my_data <-  read.csv("geum_data.csv")

graph <-ggplot(my_data, aes(exposure, seedling.count, fill = exposure)) + 
geom_col(width = 0.5) + theme(axis.title.y = element_text(margin = margin(t = 0, r = 10, b = 0, l = 0)))+
geom_text(aes(label= 76), position=position_dodge(width=0.9), vjust=-0.25) +
labs(fill = "Exposure")
graph <-  graph + labs(x = "Exposure", y = "Seedling Count avg.")
print (graph)

Upvotes: 0

Views: 40

Answers (1)

stefan
stefan

Reputation: 124083

To add the labels simply map the variable with the values on label (from your screenshot I guessed that you want to add seedling.count). Changing the colour can be achieved via scale_fill_manual. Try this:

graph <- ggplot(my_data, aes(exposure, seedling.count, fill = exposure)) + 
  geom_col(width = 0.5) + 
  scale_fill_manual(values = c(Exposed = "red", Shaded = "blue")) +
  theme(axis.title.y = element_text(margin = margin(t = 0, r = 10, b = 0, l = 0))) +
  geom_text(aes(label = seedling.count), position = position_dodge(width=0.9), vjust=-0.25) +
  labs(fill = "Exposure")

graph <- graph + labs(x = "Exposure", y = "Seedling Count avg.")
graph

Using mtcars as example data the following code shows an example of this approach:

library(ggplot2)
library(dplyr)

mtcars %>% 
  group_by(cyl = factor(cyl)) %>% 
  summarise(mpg = mean(mpg)) %>% 
  ggplot(aes(cyl, mpg, fill = cyl)) +
  geom_col() +
  geom_text(aes(label = mpg), vjust=-0.25) +
  scale_fill_manual(values = c(`4` = "red", `6` = "blue", `8` = "green"))

Created on 2020-04-19 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions