ggplot2 | How to customize the order of string values in the legend?

Viewed 53

In continuation of my earlier question, I am facing issues w.r.t. to ordering the legends. The initially posted question had ordinal (ordered) values and hence worked perfectly. In real-time, the data rendered in the legend is being ordered alphabetically.


library(ggplot2)
library(tidyverse)
library(reshape2)

#Creating a dataframe with use-case specific variables. 
df = data.frame(
  Year = 2006:2025,
  
  Survey = c(40.5, 39.0, NA, NA, NA, NA, 29.9, NA, NA, NA, 21.6,
             NA, NA, NA, NA, NA, NA, NA, NA, NA),
  
  Projected1 = c(NA, NA, NA, NA, NA, NA, 29.9, NA, NA, NA, NA,
             NA, NA, NA, NA, NA, NA, NA, NA, 14.9),
  
   WhatIf= c(NA, NA, NA, NA, NA, NA, 29.9, NA, NA, NA, NA,
             NA, NA, NA, NA, NA, NA, NA, NA, 13.0),
  
  Projected2 = c(NA, NA, NA, NA, NA, NA, 29.9, 27.6, 25.4, 23.4, 21.6,
             19.9, 18.4, 16.9, 15.6, 14.4, 13.3, NA, 12.2, 11.3)
)

#Transforming data
df <- melt(df,id.vars = "Year")

ggplot(data = NULL, aes(x=factor(Year), y=value, group=variable)) +
  geom_line(data = df[!is.na(df$value) & df$variable != "Survey",],
            aes(linetype=variable, color = variable), size = 1, linetype = "dashed")+
  geom_point(data = df[!is.na(df$value) & df$variable == "Survey",], 
             aes(color = variable), size = 4) +
  scale_color_manual(values=c('#999999', 'orange2','turquoise2','blue2'))+
  guides(color = guide_legend(override.aes = list(linetype = c("blank", "dashed", "dashed", "dashed"),
                                                  shape = c(16, NA, NA, NA)))) +
  scale_y_continuous(
    breaks=seq(0,100, 10), labels = seq(0, 100, 10), limits=c(0,70),
    sec.axis = dup_axis()) +
  theme(
    legend.position = 'bottom', legend.direction = 'horizontal',
    panel.grid.major.y = element_line(color='gray85'),
    axis.title = element_text(face='bold')) +
  
  labs(x='Year', y='measure (%)')

  Created on 2020-07-11 by the reprex package (v0.3.0)

Output

enter image description here

Objective: Sequence in the legend and respective plots must be as follows: c("Survey", "WhatIf", "Projected1", "Projected2" )


I have tried the following methods alternatively but there's no difference in the output.

  1. df$variable <- factor(df$variable, levels = c("Survey", "WhatIf", "Projected1", "Projected2" ))

  2. scale_fill_discrete(breaks = c("Survey", "WhatIf", "Projected1", "Projected2" ))

I might be missing out on a trivial step and any suggestions would be greatly helpful.

1 Answers

You just need to add a breaks = argument to scale_color_manual and change the order of values = to match because you have the guide argument set to color =:

scale_color_manual(breaks = c("Survey", "WhatIf", "Projected1", "Projected2" ),
                   values=c('turquoise2','blue2','#999999', 'orange2'))+

enter image description here

Related