简体   繁体   中英

Linetype in legend is distorted

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:

在此输入图像描述

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")

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM