简体   繁体   中英

How to add line to point shapes in ggplot2 legend

I want to create a black and white plot using ggplot2 , where the data is plotted by category using a combination of lines and points. However, the legend only shows the point shape, with no line running through it, unless I add color to the plot.

Here is some example data to illustrate the problem with:

## Create example data
set.seed(123)
dat <- data.frame(
    time_period = rep(1:4, each = 3),
    category = rep(LETTERS[1:3], 4),
    y = rnorm(12)
)

Here is an example of a color plot, so you can see how I want the legend to look:

library(ggplot2)
## Generate plot with color
ggplot(data = dat, mapping = aes(x = time_period, y = y, color = category)) +
    geom_line(aes(group = category)) +
    geom_point(aes(shape = category), size = 2) +
    theme_bw()

在此处输入图片说明

However, if I move to grayscale (which I need to be able to do), the line running through the point in the legend disappears, which I'd like to avoid:

## Generate plot without color
ggplot(data = dat, mapping = aes(x = time_period, y = y)) +
    geom_line(aes(group = category)) +
    geom_point(aes(shape = category), size = 2) +
    theme_bw()

在此处输入图片说明

How can I add a line through the point symbols in the legend with a grayscale plot?

I would suggest this approach:

#Plot
ggplot(data = dat, mapping = aes(x = time_period, y = y,group = category,shape = category)) +
  geom_line(color='gray',show.legend = T) +
  geom_point(size = 2) +
  theme_bw()

Output:

在此处输入图片说明

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