Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate geom_vline() and geom_hline() legends from other legends in ggplot2

Tags:

plot

r

ggplot2

I'm trying to create a plot in R using ggplot2 that shows horizontal lines for groundwater protection standards as well as a vertical line that shows the start of construction project. I have legends created already for units of measure and whether the sample was below the detection limit. All of these legends show up as I want them, but the legends from the horizontal and vertical line are overlain on the other legends. I've tried multiple ways using show_guide, using different data frames for the data, and override.aes = list() but nothing seems to get the desired results.

Here is what the data look like:

head(dmr_data)
    location_id sample_date analysis_result lt_measure default_unit           param_name
154        MWH1  2004-06-02          0.0150                    mg/L   Arsenic, dissolved
155        MWH1  2004-06-02          0.0850                    mg/L    Barium, dissolved
156        MWH1  2004-06-02          0.0002          <         mg/L Beryllium, dissolved
158        MWH1  2004-06-02          0.0005          <         mg/L   Cadmium, dissolved
162        MWH1  2004-06-02          0.0020          <         mg/L      Lead, dissolved
164        MWH1  2004-06-02          0.0010          <         mg/L  Thallium, dissolved
    DMR_limit  GWPS non_detect
154   0.01000 0.010          0
155   0.17340 2.000          0
156   0.00005 0.004          1
158   0.00100 0.005          1
162   0.00500 0.015          1
164   0.00060 0.002          1

And here is the code for the plot:

 combo_plot <- function(df){ 

  limits = df

  shaded_dates <- data.frame(xmin = c(as.POSIXct("2004-06-01", format = "%Y-%m-%d"), 
                                  as.POSIXct("2013-10-01", format = "%Y-%m-%d")), 
                         xmax = c(as.POSIXct("2013-10-01", format="%Y-%m-%d"), 
                                  max(df$sample_date)),
                         ymin = c(-Inf, -Inf), 
                         ymax = c(Inf, Inf),
                         years = c("background", "compliance"))

  ggplot(data = df, aes(x = sample_date, y = analysis_result)) + 
    geom_point(data = df, aes(colour = default_unit, shape = factor(non_detect)), size = 4) + 
    geom_line(data = df, aes(colour = default_unit), size = 1) +
    facet_wrap(~ param_name, scale="free") + 

# Plot legends, labels, and titles
ggtitle(paste("Time Series Plots for Monitoring Well", 
              df$location_id[1], "\n", sep=" ")) + 
ylab("Analysis Result") +
xlab("Sample Date") + scale_x_datetime(labels = date_format("%Y")) +
theme(axis.text.x = element_text(angle = 90)) +
theme(plot.margin = unit(c(0.75, 0.75, 0.75, 0.75), "in")) + 
theme_bw() + 
scale_colour_discrete(name = "Units", guide = "legend") + 

# add rectangles for date ranges
geom_rect(data = shaded_dates, aes(xmin = xmin, ymin = ymin, xmax = xmax, 
                                   ymax = ymax, fill = years),
          alpha = 0.2, inherit.aes = FALSE) +
scale_fill_manual(values=c("blue","green")) +

# add horizontal lines for EPA MCL and Upper Prediction Limit
geom_hline(data = limits, aes(yintercept = GWPS, linetype = "GWPS"), show_guide = TRUE, size = 0.75) +
geom_hline(data = limits, aes(yintercept = DMR_limit, linetype = "DMR Limit"), show_guide = TRUE, size = 0.75) +

# create custom legend using guide
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3)) +
guides(colour = guide_legend("Units"), fill = guide_legend("Dates"),
       linetype = guide_legend("Limits")) +
scale_shape_manual(name = "Measure", labels = c("Non-Detect", "Detected"),
                   values = c("1" = 21, "0" = 4)) + 

# add vertical line to show start of "East Pushout" construction
geom_vline(xintercept = as.numeric(as.POSIXct("2008-08-01", format="%Y-%m-%d")),
           linetype="dotted", show_guide = T)

}

I then use plyr to create faceted plots for all the wells

d_ply(dmr_data, .(location_id), .progress = "text", failwith(NA, combo_plot), .print = TRUE)

Here is what the ouput looks like. enter image description here Any help would be appreciated!

like image 422
jentjr Avatar asked Dec 11 '13 19:12

jentjr


1 Answers

You can get the desired effect by using override.aes = list(linetype = 0) in guides(), and by adding a new scale for linetype (so as to exclude the vertical construction line from showing up in the legend).

Replace your hline() section with:

## add horizontal lines for EPA MCL and Upper Prediction Limit
geom_hline(data = limits, aes(yintercept = GWPS, linetype = "GWPS"), colour = "black", size = 0.75, show_guide = T) +
geom_hline(data = limits, aes(yintercept = DMR_limit, linetype = "DMR Limit"), size = 0.75, show_guide = T) +
scale_linetype_manual(name = "Limits", labels = c("GWPS", "DMR Limit"), values = c("GWPS" = 1, "DMR Limit" = 2)) +

Replace your guides() line with:

guides(colour = guide_legend(override.aes = list(linetype = 0 )), 
       fill = guide_legend(override.aes = list(linetype = 0 )), 
       shape = guide_legend(override.aes = list(linetype = 0 )), 
       linetype = guide_legend()) +

If you do want the dotted vertical line to show up in the legend, add the appropriate arguments to geom_vline(aes()) and to scale_linetype_manual().

like image 120
Nate Pope Avatar answered Oct 31 '22 19:10

Nate Pope