Reputation: 2891
I have a plot that shows the memory usage of some function over time, for two different versions of the function. Now, for each version I added a dashed regression line. So I added a legend (with scale_linetype_manual
) which clarifies that solid lines represent the actual measurements and dashed lines represent the regression line. However, there is something wrong with the dashed line in the legend and I can't find out what is causing this:
The problem is more clear when i use a dotted line for the regression line instead of a dashed line. Those smaller extra dots should not be in the legend:
Here is the relevant part of my R script:
ggplot(df, aes(x = x, y = heapUsage, color=Version)) +
geom_line(aes(lty="data")) +
geom_smooth(method='lm', se=TRUE, aes(lty="trend")) +
scale_linetype_manual("Data", values=c("solid", "dotted"), breaks=c("data", "trend"), labels=c(" Measured ", " Regression line")) +
theme_bw() +
theme(legend.position = "top") +
guides(color=guide_legend(override.aes=list(fill=NA))) +
guides(linetype=guide_legend(override.aes=list(fill=NA, color="black"))) +
labs(x = "# Executed Operations") +
labs(y = "Heap Usage in MB")
And here is what the entire plot looks like:
Upvotes: 2
Views: 580
Reputation: 50718
The issue arises from both geom_line
and geom_smooth
drawing a legend that gets overlayed.
You can switch off the legend for geom_smooth
by adding show.legend = FALSE
. Here is a reproducible example based on mtcars
. If you omit show.legend = FALSE
(or set show.legend = TRUE
) you will see the overlay effect of the black and blue lines in the legend.
mtcars %>%
select(mpg, disp, qsec) %>%
gather(k, v, -mpg) %>%
ggplot(aes(mpg, v, linetype = k)) +
geom_smooth(method = "lm", se = T, show.legend = F) +
geom_line() +
scale_linetype_manual("Data", values=c("solid", "dotted")) +
theme_bw() +
theme(legend.position = "top")
Upvotes: 3