The issue here is the use of multiple data frames to store values. It would be better to add a column to the mydf
data frame to store the direction
variable. Confusingly, you have used answer
as the variable name in mydf
, but direction
to store the same values in the other data frames.
So here is the new mydf
with values "up", "down" or NA in the direction
column:
mydf <- structure(structure(list(year = c(2000, 2000, 2000, 2002, 2002, 2002, 2004,
2004, 2004, 2006, 2006, 2006, 2008, 2008, 2008, 2010, 2010, 2010,
2012, 2012, 2012, 2014, 2014, 2014, 2016, 2016, 2016), answer = structure(c(1L,
2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L,
3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("A great deal",
"Hardly any", "Only some"), class = "factor"), result = c(0.301594,
0.1399303, 0.5584757, 0.2269548, 0.1792754, 0.5937698, 0.2955301,
0.1309859, 0.573484, 0.3008197, 0.1344499, 0.5647303, 0.1919454,
0.202629, 0.6054256, 0.1059793, 0.4190533, 0.4749674, 0.1190636,
0.3631279, 0.5178085, 0.1518314, 0.3181203, 0.5300483, 0.1424715,
0.3094615, 0.5480669), direction = c(NA, NA, NA, "down", NA,
NA, "up", NA, NA, NA, NA, NA, "down", "up", NA, "down", "up",
"down", NA, "down", NA, NA, NA, NA, NA, NA, NA)), .Names = c("year",
"answer", "result", "direction"), row.names = c(NA, -27L), class =
"data.frame"))
Now you can plot with separate legends for direction
and answer
. Shapes are specified manually using scale_shape_manual
, using breaks
to omit the NA values. For line colour, we use scale_color_manual
and override the legend mapping so as only lines, not shapes, are shown.
ggplot(mydf, aes(year, result)) +
geom_line(aes(group = answer, color = answer)) +
geom_point(aes(shape = direction, fill = answer), size = 3) +
scale_shape_manual(values = c(25, 24), breaks = c("down", "up")) +
scale_color_manual(values = c("red", "green", "blue"),
guide = guide_legend(override.aes = list(shape = rep(NA, 3)))) +
theme_light()