Add an additional staple to geom_col with value zero R

186 views Asked by At

I have a dataset of different species and different damage. As you can see in my data, I only have two different "damages" in my code, but in a matter of fact, I got three different "damages". I want to plot my data and for each Species (Wolf, Bear, and Wildboar). I want staples for damage1 (grazing), damage2(stomp), and damage3, etc. But I want the staple for the damage3 to be "zero". I want to show in some way that there were zero species in damage3.

data <- data.frame(Species=c("Wolf", "Wolf", "Bear", "Bear", "Woldboar", "Wolf", "Wolf", "Bear", "Bear", "Wildboar"), Damage=c(rep("Grazing", 5),rep("Stomp", 5)))


data$Species<- factor(data$Species, levels=c("Wolf","Bear", "Wildboar"))

data <- data.frame(table(data))

ggplot(data) + 
  aes(x = Species, y = Freq, fill = Damage) + 
  geom_col(position = "dodge2", col = "black") + 
  ylab("Count") + 
  xlab("Species") + 
  theme_classic() +
  scale_x_discrete(drop = FALSE) +
  theme(legend.position = "top") +
  scale_fill_discrete(labels = c("Grazing", "Stomp", "Fear"), drop = FALSE)

I have tried with scale_fill_discrete(drop = FALSE), but it didn't work. Have anyone else experienced the same problem?

2

There are 2 answers

1
Ronak Shah On BEST ANSWER

Would adding text on top of bars with count work ?

library(ggplot2)

ggplot(data) + 
  aes(x = Species, y = Freq, fill = Damage, label = Freq) + 
  geom_col(position = "dodge2", col = "black") + 
  ylab("Count") + 
  xlab("Species") + 
  geom_text(position = position_dodge(width = 1), vjust = -0.5, size = 5) +
  theme_classic() +
  scale_x_discrete(drop = FALSE) +
  theme(legend.position = "top") +
  scale_fill_discrete(labels = c("Grazing", "Stomp", "Fear"), drop = FALSE)

enter image description here

0
Jonny On

One option is to specify the factor levels of all the Damages, just as you did for the Species:

library(tidyverse)

data <- data.frame(Species=c("Wolf", "Wolf", "Bear", "Bear", "Woldboar", "Wolf", "Wolf", "Bear", "Bear", "Wildboar"), Damage=c(rep("Grazing", 5),rep("Stomp", 5)))

data$Species<- factor(data$Species, levels=c("Wolf","Bear", "Wildboar"))

# Set factor levels for damages, adding in a third level (Fear)
data$Damage<- factor(data$Damage, levels=c("Grazing","Stomp", "Fear"))

data <- data.frame(table(data))

ggplot(data) + 
  aes(x = Species, y = Freq, fill = Damage) + 
  geom_col(position = "dodge2", col = "black") + 
  ylab("Count") + 
  xlab("Species") + 
  theme_classic() +
  scale_x_discrete(drop = FALSE) +
  theme(legend.position = "top")

Created on 2020-10-13 by the reprex package (v0.3.0)

You can then drop the scale_fill_discrete()