Reputation: 11
the idea is simple:
(1)Use red dot for actual data;
(2)Use blue dashed line for fitted value.
But I just could not find a way to make such legend.
My fig and code below:
library(ggplot)
x <- seq(1,100,1)
y <- 2*x + runif(100,-5,5)
fit_y <- 2*x
df <- data.frame(x=x, y=y,fit_y=fit_y)
df
ggplot(df)+
geom_point(aes(x=x, y=y, color='point', shape='point'))+
geom_line(aes(x=x, y=fit_y, color='line', linetype='line')) +
scale_color_manual(values=c('point'='red', 'line'='blue')) +
scale_linetype_manual(values = c('line'='longdash')) +
scale_shape_manual(values = c('point'=1 ))
And I am pretty confused about that: Why is color legend composed of line and point?
Now it is a "blue line + blue point" PLUS "red line + red point".
But I only assign red to geom_point and blue to geom_line! Why is this?
Upvotes: 1
Views: 379
Reputation: 37933
Perhaps the best way is to not bother mapping aesthetics for shape and linetype at all, and instead overriding the display of the colour legend directly. This is also the suggested workaround for guides indiscriminately applying glyphs for every key.
library(ggplot2)
x <- seq(1,100,1)
y <- 2*x + runif(100,-5,5)
fit_y <- 2*x
df <- data.frame(x=x, y=y,fit_y=fit_y)
ggplot(df)+
geom_point(aes(x=x, y=y, color='point'),
shape = 1)+
geom_line(aes(x=x, y=fit_y, color='line', linetype='line'),
linetype = 'longdash') +
scale_color_manual(
values=c('point'='red', 'line'='blue'),
guide = guide_legend(
override.aes = list(
shape = c(1, NA),
linetype = c(NA, 5)
)
)
)
Created on 2021-05-17 by the reprex package (v1.0.0)
Upvotes: 1
Reputation: 2650
is this what you're looking for?
ggplot(df)+
geom_point(aes(x=x, y=y, color="real"), shape=1)+
geom_line(aes(x=x, y=fit_y, linetype="estimate"), color="blue") +
scale_color_manual(name="", values=c(real="red")) +
scale_linetype_manual(name="", values = c(estimate="longdash")) +
theme(legend.position="bottom")
The issue is that they are not really combined, they are still two separate legends, which is why I add the legend at the bottom, it looks more like one legend
Upvotes: 0
Reputation: 1
If I'm not mistaken, you want your data to be blue dots and your fitted value to be red dashed line.
I tried to make some adjustments on your code like following:
ggplot(df)+
geom_point(aes(x=x, y=y, color='point', shape='point'))+
geom_line(aes(x=x, y=fit_y, color='line', linetype='line')) +
scale_color_manual(values=c('point'='blue', 'line'='red')) +
scale_linetype_manual(values = c('line'='longdash')) +
scale_shape_manual(values = c('point'=1 ))
And so that I got following graph:
Upvotes: 0