0
votes

I am trying to overlay a line plot onto a barplot. I can plot both separately :

##plot sites
ggplot(graph, aes(x = Month, y = Anopheles_pos))
+ geom_col(size = 1, color = "darkblue", fill = "white") 

enter image description here

##plot line
ggplot(graph, aes(x = Month, y = Mean_EVI)) +
 geom_line(size = 1.5, color = "blue", group = 1)

enter image description here

However when I try to plot the line onto the barplot, it is a flat line at the bottom. I tried to deal with the issue by fixing the second y axis (on the right) to be the same scale as the line, but this has not fixed how the line plots.

##plot together
    ggplot(graph) + 
      geom_col(aes( x = factor(Month, levels = month.name), y = Anopheles_pos), size = 1,
                    color = "darkblue", fill = "white") + 
      geom_line(aes(x = factor(Month, levels = month.name), y = Mean_EVI), size = 1.5, 
                color = "red", group = 1) +
     scale_y_continuous(sec.axis = sec_axis(~./50, name = "Mean_EVI"))

enter image description here

One small other issue is I can't figure out how to make the x axis 0-100 as the Anopheles_pos values are percentages.

Thanks in advance!!

DATA:

Mean_EVI : c(0.5687068, 0.5663895, 0.5653846, 0.6504931, 0.584727, 0.5799395, 0.617363, 0.581645, 0.6190386, 0.5208025, 0.6097692, 0.5689)

Anopheles_pos : c(33L, 42L, 38L, 31L, 54L, 47L, 22L, 15L, 2L, 15L, 12L, 19L)

1

1 Answers

2
votes

You need to scale up your Mean_EVI values by 50 to match the ./50 part of your sec.axis call.

Mean_EVI <- c(0.6190386, 0.5208025, 0.6097692, 0.5689, 0.5687068, 0.5663895, 0.5653846, 0.6504931, 0.584727, 0.5799395, 0.617363, 0.581645)

Anopheles_pos <- c(2L, 15L, 12L, 19L, 33L, 42L, 38L, 31L, 54L, 47L, 22L, 15L)

graph <- data.frame(Mean_EVI, Anopheles_pos, Month = 1:12)

ggplot(graph) + 
  geom_col(aes(x = factor(Month, labels = month.name), y = Anopheles_pos), size = 1,
           color = "darkblue", fill = "white") + 
  geom_line(aes(x =  factor(Month, labels = month.name), y = Mean_EVI*50), size = 1.5, 
            color = "red", group = 1) +
  scale_y_continuous(sec.axis = sec_axis(~./50, name = "Mean_EVI")) +
  coord_cartesian(ylim = c(0, 100))

enter image description here