简体   繁体   中英

Controlling linetype, color and label in ggplot legend

I'm having trouble setting custom legend labels on plots where I have also previously specified custom linetypes and colors. There is a similar question on stackoverflow that deals with custom legends for linetypes and line colors . However, once you wish to specify legend labels on top of the two aforementioned attributes ggplot2 seemingly starts to break down.

Here's my minimally reproducible example:

library(ggplot2)

df <- data.frame(x = rep(1:2, 2), y = c(1, 3, 2, 2),
           treatment = c(rep("one", 2), rep("two", "2")))

ggplot(df, aes(x = x, y = y, colour = treatment, linetype = treatment)) +
  geom_line() +
  scale_linetype_manual(values = c(1, 3),
                        labels = c("Treatment one", "Treatment two")) +
  scale_color_manual(values = c("black", "red"))

The above code results in the following graph

在scale_linetype_manual或scale_color_manual中设置标签会导致创建两个图例。

Setting labels in either scale_linetype_manual() or scale_color_manual() results in two seperate legends being created. The one that has the correct dashing of lines will always be colorless. The one with correct colors, on the other hand, will not represent the linetypes correctly (only solid lines).

Is there a way to control color, line type and legend labels all at once in ggplot2? Or is this a limitation of the package where I should just specify the labels correctly in the dataframe from the getgo?

Make the label the same for both scale_linetype_manual() and scale_color_manual() .

library(ggplot2)

df <- data.frame(x = rep(1:2, 2), y = c(1, 3, 2, 2),
                 treatment = c(rep("one", 2), rep("two", "2")))

ggplot(df, aes(x = x, y = y, colour = treatment, linetype = treatment)) +
  geom_line() +
  scale_linetype_manual(values = c(1, 3),
                        labels = c("Treatment one", "Treatment two")) +
  scale_color_manual(values = c("black", "red"),
                     labels = c("Treatment one", "Treatment two"))

在此处输入图片说明

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