Anson Biggs
Anson Biggs

Reputation: 342

How to use ggplot2 legend to denote different geoms

I am using ggplot2 to plot points from a .csv file that is just a column used a x values and a column used a y values. I am a little confused as to how ggplot decides what to make a legend for and haven't found any good examples online.

I would like the legend to show that geom_point is stress vs strain, and my geom_smooth is the best fit line.

Here is my code:

library(ggplot2)
imported = read.csv("data.csv")

Strain = imported$Strain
Stress = imported$Stress..N.m.2.
err = .0005

gg <-
  ggplot(imported, aes(x=Strain, y=Stress)) + 
  geom_point(aes(group = "Points"), shape = 79, colour = "black", size = 2, stroke = 4) + 
  geom_smooth(method = "lm", se = FALSE, color = "orange") + 
  geom_errorbarh(xmin = Strain - err, xmax = Strain + err, show.legend = TRUE) + 
  theme_gray() + ggtitle("Stress vs Strain") + 
  theme(legend.position = "top")

gg 

And it is producing the following plot: my plot

Upvotes: 2

Views: 1584

Answers (1)

Jon Spring
Jon Spring

Reputation: 66415

Edit: added approach at top to create legend for each geom, by creating dummy mapping to separate aesthetics.

library(ggplot2)
ggplot(mtcars, aes(mpg, wt)) +
  geom_point(aes(color = "point")) +   # dummy mapping to color
  geom_smooth(method = "lm", se = FALSE, color = "orange",
               aes(linetype = "best fit")) +  # dummy mapping to linetype
  geom_errorbarh(aes(xmin = mpg - 2, xmax = mpg + 1)) +

  scale_color_manual(name = "Stress vs. Strain", values = "black") +
  scale_linetype_manual(name = "Best fit line", values = "solid")

enter image description here


original answer:

Note the difference in legend here:

library(ggplot2)
ggplot(mtcars, aes(mpg, wt, color = as.character(cyl))) +
    geom_point() +
    geom_errorbarh(aes(xmin = mpg - 2, xmax = mpg + 1), 
      show.legend = TRUE)  # error bars reflected in legend

with error bar in legend

ggplot(mtcars, aes(mpg, wt, color = as.character(cyl))) +
    geom_point() +
    geom_errorbarh(aes(xmin = mpg - 2, xmax = mpg + 1), 
      show.legend = FALSE)   # error bars not shown in legend

without error bar in legend

Upvotes: 5

Related Questions