mountainscaler
mountainscaler

Reputation: 179

Adding grouped geom_vline to multiple facets

I am trying to add vertical lines that should be specific to each plot facet. I am attempting to do this by grouping the geom_vline data by the same process as the plot data are grouped. The vertical data are from a different dataframe than the points are. The lines of code below are what I have.

plots <-
  dd %>%
   ggplot(aes(Date, TDS)) +
    theme_bw() +
    geom_point(aes(group = Well, color = Well), size = 1) +
    ggtitle(paste("WMA A-AX TDS")) +
    ylab("mg/L") +
    geom_smooth(aes(group= Well), method = "loess", color = "black",  se = FALSE) +
    geom_vline(data = cpdates, aes(group = Well_LOC, xintercept=as.numeric(CPT_DATE)), color ="blue", lwd=0.5, lty=1) +
    facet_grid(Well~.)

This code however does not group the geom_vline data but puts all of the lines in all of the facets. The grouping works for the points and the LOESS lines so why not the vlines?

Example plot with excess vertical lines in facets

I have tried numerous things to solve this but nothing works. Any and all suggestions would be greatly appreciated.

Upvotes: 5

Views: 4144

Answers (1)

Paul
Paul

Reputation: 9087

Facets don't use the group aesthetic. The plot is faceting on Well, so cpdates needs a Well variable.

Here is some dummy data to reproduce the problematic plot.

library('ggplot2')
library('dplyr')

cpdates <- data.frame(
  Well_LOC = c(4, 5, 6, 8),
  CPT_DATE = c(1, 2, 3,4))

dd <- data.frame(
  Date = mpg$displ,
  TDS = mpg$cty,
  Well = mpg$cyl)


dd %>%
 ggplot(aes(Date, TDS)) +
  theme_bw() +
  geom_point(aes(group = Well, color = Well), size = 1) +
  ggtitle(paste("WMA A-AX TDS")) +
  ylab("mg/L") +
  geom_smooth(aes(group = Well), method = "loess", color = "black",  se = FALSE) +
  geom_vline(data = cpdates, aes(group = Well_LOC, xintercept=as.numeric(CPT_DATE)), color ="blue", lwd=0.5, lty=1) +
  facet_grid(Well~.)

bad plot

Adding Well to cpdates fixes the problem. We can also get rid of the group asthetic.

cpdates$Well = cpdates$Well_LOC

dd %>%
 ggplot(aes(Date, TDS)) +
  theme_bw() +
  geom_point(aes(group = Well, color = Well), size = 1) +
  ggtitle(paste("WMA A-AX TDS")) +
  ylab("mg/L") +
  geom_smooth(method = "loess", color = "black",  se = FALSE) +
  geom_vline(data = cpdates, aes(xintercept=as.numeric(CPT_DATE)), color ="blue", lwd=0.5, lty=1) +
  facet_grid(Well~.)

fixed plot

Upvotes: 6

Related Questions