Is there a way to add multiple horizontal lines to a plot with different symbology and a legent?

52 views Asked by At

I need to add horizontal lines (similar to geom_hline) to a plot but retain the ability to add symbology (e.g. different dashed or dotted line) to each and have them appear in a legend. The y-intercept of each comes from the "Concentration" variable and the label needs to come from "Type". I've created an example dataset at the bottom of the question but the one I'm working with is a lot larger, with about 30 different Pesticides and up to 4 Types within each. I am hoping to split and sapply to automate plotting across the entire dataset.

Here is the plot code that I've tried so far and you can see the geom_hline works (as in, the lines appear on the plot), but it doesnt give the ability to change symbology of each or add a legend. Please ignore the box plots and jitter - they arent relevant to this question.

Is there a way i can add these lines to the plot, each with different symbology and a legend to capture that?

Thanks in advance

Plot2 <- ggplot(PestDat, aes(x=factor(Phyla), y=Conc_ug)) +
  geom_boxplot(color="dark gray", fill = 'dark gray', alpha = 0.1) +
  geom_jitter(aes(shape = Pathway), height=.3, width=.3, size = 1.5) +
  scale_y_continuous(trans='log10') +
  geom_hline(data = PestDat,aes(yintercept = Concentration),linetype="dashed") +
  labs(x = "Phyla", y = "Log10 Concentration (µg/L)") +
   labs(title = (unique(ToxDat_Diuron$Pesticide)),
         subtitle = "Do we want a subtitle for the plot?",
        caption = "Source: Citation, Reliability ?? ")
           Plot2 

enter image description here

Sample data

PestDat <- data.frame(
     Pest = c("Diuron","Diuron","Diuron","Diuron","Atrazine"),
     Type = c("PC99","PC95","PC90","PC80","ETV"),
     Concentration = c(0.1,0.2,0.3,0.4,0.7),
     stringsAsFactors = FALSE)
1

There are 1 answers

2
Jon Spring On

We can put the linetype aesthetic inside the aes() term to make it use the variable from the data to categorize the type of line. Note that linetype wants a discrete variable, so in this case I used A-B-C.

ggplot(PestDat, aes(x=factor(Pest), y=Concentration)) +
  geom_boxplot(color="dark gray", fill = 'dark gray', alpha = 0.1) +
  geom_jitter(aes(shape = Type), height=.3, width=.3, size = 1.5) +
  scale_y_continuous(trans='log10') +
  labs(x = "Phyla", y = "Log10 Concentration (µg/L)",
       subtitle = "Do we want a subtitle for the plot?") +
  geom_hline(data = data.frame(y_int = c(0.6,0.9, 1.1),
                               type = c("C","B","A")),
             aes(yintercept = y_int, linetype = type))

enter image description here