简体   繁体   中英

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

I need to add horizontal lines (similar to geom_hline) to a plot but retain the ability to add symbology (eg 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 

在此处输入图像描述

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)

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

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))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM