Maral Dorri
Maral Dorri

Reputation: 478

How to change color legend from continues to discrete colors in ggplot2?

I have created a line graph using ggplot2 and the color legend is continuous. I would like to change that to discrete colored lines. I have the following code:

library(ggplot2)
ggplot(df, aes(L)) +
 geom_line(aes(y = Updated, colour = S, group = S, linetype = "Updated")) +
 geom_line(aes(y = Current, colour = S, group = S, linetype = "Current")) +
 scale_color_gradient() +
 labs(x = element_text("Span Length (ft)"), y = element_blank(), 
         title = "Moment Live Load Distribution Factors \n Exterior Girder - Multi Lane",
      linetype = "AASHTO", color = "Spacing (ft)") +
  scale_linetype_manual(values = c(1, 3),
                        labels = c("Updated", "Current")) +
    theme_classic() +
    theme(plot.title = element_text(hjust = 0.5, margin = margin(0,0,20,0), size = 18),
          legend.position="top",
          legend.box.background = element_rect(colour = "black", size = 0.5),
          legend.box.margin = margin(0,0,0,0), legend.background = element_blank())

At the moment my graph looks like enter image description here

I would like to convert the continuous part of the legend to just colored lines with the same width as the remainder of the legend. Thank you!

Upvotes: 0

Views: 2186

Answers (1)

GGamba
GGamba

Reputation: 13680

You have multiple options, depending on the meaning of the variable:

Transform the variable to a factor:

library(ggplot2)


ggplot(mtcars) +
  geom_line(aes(mpg, wt, colour = factor(cyl)))

Created on 2020-04-15 by the reprex package (v0.3.0)

Use a binned legend:

ggplot(mtcars) +
  geom_line(aes(mpg, wt, colour = cyl)) +
  scale_color_binned(guide = guide_coloursteps())

Created on 2020-04-15 by the reprex package (v0.3.0)

Note that guide = guide_coloursteps() does nothing at the moment, but can help you customize the legend.

Upvotes: 1

Related Questions