shirewoman2
shirewoman2

Reputation: 1928

R: In ggplot2, how do you combine linetype and color when they're set by different variables?

I've got a line graph where the linetype is set by one variable (SampleType, in this example) and the color is set by another (Sample). For these data, I'd like it if the legend combined both of those variables into one legend entry rather than having one entry for the color and one for the linetype. Here are my example data: EIC data

Here is the code and the plot I've come up with so far:

 EIC <- read.csv("EIC data.csv")
 ggplot(EIC, aes(x = Time, y = Counts, color = Sample, linetype = SampleType)) +
        geom_line()

Line plot of extracted ion chromatograms

What I'd really like is for the legend to just show "Sample" and then the appropriate colors AND linetypes for each of those samples, so it would be solid for the standards and dashed for the clinical samples and each sample would be a different color. I love ggplot2, so I'd prefer to continue to use ggplot2 to do this. I've tried adding scale_linetype_manual like this to the code:

 scale_linetype_manual(values = c(rep("solid", 3), rep("dashed", 2)))

but that's not changing the legend or the graph. I've also tried making a new column with "solid" or "dashed" in each row depending on whether the sample is a clinical sample or a standard and then using scale_linetype_identity(), but while that does work for the graph, it's not changing the legend since I'm still mapping color to one variable and linetype to a second.

I'm using R version 3.0.2 and ggplot2_1.0.0.

Thanks in advance for any ideas!

Upvotes: 1

Views: 5012

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98429

Use variable Sample for both - color= and linetype= and then with scale_linetype_manual() get the desired linetypes.

ggplot(EIC, aes(x = Time, y = Counts, color = Sample, linetype = Sample)) +
      geom_line()+scale_linetype_manual(values = c(rep("solid", 3), rep("dashed", 2)))

enter image description here

Upvotes: 7

Related Questions