简体   繁体   中英

Change ggplot2 legend to distinguish linetype (solid and longdash look similar)

I am preparing a legend for publication and I am wondering how I can change the 'phase' of the linetype legend so that the difference between dotted, solid and longdash is clear. I think this feature is really lacking something. With default settings the longdash is for instance indistingusihable from solid.

Here is what I got:
在此处输入图像描述

Ideally I'd like the empty part of the longdash line to be in the middle. Alternative, is there way to change the length of lines that are displayed without changing the size of the whole legend? Maybe it would enough to take more of the empty space where the line ends and the legend.text beginns (eg making the lines longer).

Here is reproducible code:

library(ggplot2)
library(cowplot)

varLabels <- factor(c(rep('var1', 100), rep('var2', 100), rep('var3', 100)), 
                     levels = c("var1", "var2", "var3"))

df <- data.frame(var  = varLabels,
                 x    = rep(1:100, 3),
                 y    = c(rnorm(100), rnorm(100), rnorm(100)))

plt1 <- ggplot(data = df, aes(x = x, y = y)) + 
  geom_line(aes(linetype = var), size = 0.5) + 
  scale_linetype_manual(values=c("dotted", "solid", 'longdash')) +
  theme(legend.text = element_text(size = 5),
        legend.title = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        axis.title.x = element_text(size = 8),
        axis.title.y = element_text(size = 8))

# Get and save legend
legend <- cowplot::get_legend(plt1)
ggsave(filename = 'legend2.jpeg', legend, width = 2, height = 2, dpi = 1000, units = c("cm"))

You can adjust legend.key.size in your call to theme :

plt2 <-  plt1 + theme(legend.key.size = unit(0.75, "cm"))
legend <- cowplot::get_legend(plt2)
ggsave(filename = 'legend2.jpeg', legend, width = 2, 
       height = 2, dpi = 1000, units = c("cm"))

Yielding this:

在此处输入图像描述

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