Search code examples
rggplot2plotpivotlegend

ggplot2: remove alphabetic order in the legend after the pivot of the dataset


This is a sample of my dataset

                 Year North Center South
                 <dbl> <dbl>  <dbl> <dbl>
 1                1995 1115.  1057.  876.
 2                1996 1559.  1461. 1196.
 3                1997 1956.  1923. 1454.
 4                1998 1595.  1544. 1139.
 5                1999 1912.  1632. 1199.
 6                2000 1838.  1868. 1331.
 7                2001 1550.  1613. 1204.
 8                2002 1598.  1565. 1749.
 9                2003 1590.  1654. 1182.
10                2004 1906.  1666. 1203.
11                2005 1523.  1701. 1149.
12                2006 1697.  1741. 1233.
13                2007 1601.  1773. 1267.
14                2008 1937.  1999. 1397.
15                2009 1989.  1330. 1696.
16                2010 1771.  1843  1766.
17                2011 1936.  2529. 1478.
18                2012 1445.  1527. 1745.

and this is my code

df %>% 
  pivot_longer(cols=-`Year`, names_to="area", values_to="value")%>%
  ggplot(aes(x=factor(`Year`), y=value, group=area, color=area)) +
  geom_point() +
  geom_line() 

The problem is that ggplot sets the legend in the alphabetic order, instead I need it as North-Center-South

I have already tried

scale_fill_discrete(breaks=c("North","Center","South")

But nothing happens... how can I solve??


Solution

  • Try this using scale_color_discrete to change the order.

    df %>% 
      pivot_longer(cols=-Year, names_to="area", values_to="value") %>%
      ggplot(aes(x=factor(`Commencement Year`), y=value, group=area, color=area)) +
      geom_point() +
      geom_line() +
      geom_hline(data = . %>% filter(area == "North"), aes(yintercept = mean(value)), color = "red", linetype = "dashed") +
      scale_x_discrete(guide = guide_axis(n.dodge = 2)) +
      scale_color_discrete(limits = c("North", "Center", "South"))