1

I have the following code to create the attached plot, essentially I want to show the abundances from May - September. But there are no abundances in May, August and September. Is there a way I can include those month in my plot even though there is no data for those monthsenter image description here in my data frame?

coef <- 625
HerringJCO <- JCOHattacksnoduplicates %>% 
mutate(month = as.factor(month),
     herringmean = herringmean/coef) %>% 
pivot_longer(cols = c("herringmean","jcoaverage"), names_to = "species", 
values_to = "mean") %>% 
ggplot(aes(x = month, group = species)) +
geom_bar(aes(y = mean, fill = species), stat = "identity", position = 
"dodge") +
geom_line(aes(y = attacksum, group = 1)) +
geom_point(aes(y = attacksum)) +
geom_line(aes(y = passivesum, group = 1), color = "green") +
geom_point(aes(y = passivesum), color = "green") +
scale_y_continuous(expand = c(0,0), limits = c(0,35), sec.axis = 
sec_axis(~.*coef, name = "Average Herring Abundance")) +
ylab("Average Salmon Abundance and Sum of attacks") +
xlab("") +
theme_classic() +
theme(axis.text.x = element_text(size = "14")) +
scale_x_discrete(labels=c("4"="April", "5" = "May", "6" = "Jun", "7" = 
"Jul", [![enter image description here][1]][1]"8" = "Aug", "9" = "Sept", "10" = "Oct")) +



HerringJCO
  • 3
    While you have code here, we don't have your data so cannot reproduce anything. Since you're asking about plotting, do we need to see all of your dplyr code? I'd think we could look at sample data after that point, and do *just* ggplot-things. – r2evans Jan 21 '22 at 21:34

1 Answers1

1

You could always add those months to the data, but make the values you aggregated equal to 0, so it would show on your chart, with a value of zero.

I created some fake data and left the lines and points off. However, if you just add the months in, but give them no value for what you have stored in mean, it will show the months with no bars.

library(tidyverse)

hjo <- data.frame(month = rep(5:9, 2) %>% as.factor(),
                  species = rep(c("herr", "jcoa"), 5),
                  values = c(0,5,8,0,0,0,4,5,0,0))

ggplot(hjo, aes(x = month, group = species, fill = species)) + 
  geom_col(aes(y = values), position = "dodge") +
  scale_y_continuous(expand = c(0,0), limits = c(0,35), sec.axis = 
                       sec_axis(~.*coef, name = "Average Herring Abundance")) +
  ylab("Average Salmon Abundance and Sum of attacks") +
  xlab("") +
  theme_classic() +
  theme(axis.text.x = element_text(size = "14")) +
  scale_x_discrete(labels = month.abb[5:9])

Check it out:

enter image description here

However, I do want to point out that what @r2evans mentioned is really important in a language that is extremely flexible. Seeing how the data you're using is structured is the best way to get great answers quickly.

There are a lot of resources about how to make that happen, like this one: making R reproducible questions.

Kat
  • 15,669
  • 3
  • 18
  • 51