0

I want to plot points (datpoint) and a fitted curve (datline) on a same graph with ggplot2 and I need to see the legend for my points and for the fitted curve. Unfortunatly, ggplot2 only draws the legend for the points and not for the line. I tried different ggplot options like scale_linetype_manual, scale_colour_manual and other one but the result is not the expected one. The aesthetics arguments seem badly used.

library(ggplot2)

datpoint <- structure(list(conc = c(0, 0.074, 0.22, 0.66, 0, 0.074, 0.22, 0.66, 0, 0.074, 0.22, 0.66),
        resp = c(2.9324, 3.1687, 2.6380, 0.5360, 3.3622, 3.2655, 2.7124, 0.0905, 3.1875, 3.0549, 2.7410, 0.1085), 
        mortality = c(1, 1, 1, 1, 19, 1, 1, 19, 1, 1, 19, 1)), 
        .Names = c("conc", "resp", "mortality"), row.names = c(NA, -12L), class = "data.frame")

datline <- structure(list(X = c(0, 0.06, 0.1266, 0.1933, 0.26, 0.3266, 0.3933, 0.46, 0.5266, 0.5933, 0.66), Y = c(3.1470, 3.1463, 3.1241, 2.9947, 2.6272, 2.013, 1.3566, 0.8493, 0.5218, 0.3248, 0.2076)), .Names = c("X", "Y"), row.names = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L), class = "data.frame")

fitcol = "red"
fitlty = 1
fitlwd = 1
legend.title = "Mortality"

fg <- ggplot(datpoint, aes(conc, resp,  color = factor(mortality))) + 
geom_point(size = 2.5) +
geom_line(aes(X,Y), datline , color = fitcol, linetype = fitlty, size = fitlwd) +
scale_colour_hue(legend.title, breaks = c("1","19"), labels = c("dead", "alive")) +
labs(x = "conc", y = "resp")

fg

Any help to draw the legend for the points and the Fitted curve with correct title (Fitted curve) would be much appreciated. Thanks!

Jaap
  • 81,064
  • 34
  • 182
  • 193
Philippe
  • 194
  • 1
  • 12

1 Answers1

1

You need to map a colour in aes to have it appear in the legend:

fg <- ggplot(datpoint, aes(conc, resp,  color = factor(mortality))) + 
  geom_point(size = 2.5) +
  geom_line(aes(X,Y, color = "fit"), datline , 
            linetype = fitlty, size = fitlwd) +
  scale_colour_hue(legend.title, breaks = c("1","19", "fit"), 
                   labels = c("dead", "alive", "fit")) +
  labs(x = "conc", y = "resp")

fg

enter image description here

Roland
  • 127,288
  • 10
  • 191
  • 288
  • Ok Thanks, this use of aesthetics arguments can be an alternative, but it is not the expected result. Here, points and lines have the same type of symbol and we can't choose the color of the curve. I need to have the two correct types of symbol and it is important to have the possibility to choose the color of the curve: points for the points and a line for the line. An generic code equivalent code can be: legend("topright", title = "Mortality", pch = c(19, 1, NA), lty = c(0, 0, fitlty), lwd = c(1, 1, fitlwd), col = c(1, 1, fitcol), legend = c("No", "Yes", "Fitted curve"), bty = "n") – Philippe May 23 '14 at 16:57
  • I have a very similar problem, but want to change also the legend, so that lines appear as lines only and points only as points. – tpetzoldt May 04 '20 at 08:03