Search code examples
rggplot2time-serieslinechart

Adding labels to a line plot with ggplot2


I am trying to add like a legend on the right that indicates the variable name. In the data frame, the lines are columns named "Correctional Spending" or "Medicaid Spending", and I want those to be shown. Can someone help please?

Here is my plot: enter image description here

Here is my code:

ggplot(Alabama, aes(x=AlYear)) + 
  geom_line(aes(y = AlMed), color = "darkred") + 
  geom_line(aes(y = AlCorr), color="steelblue", linetype="twodash") +
  labs(title='Figure 3: Alabama Social Spending',
        x='Fiscal Year', y= 'Spending (in $100,000')

Solution

  • This is because the type of spending (Coor or Med) is actually a variable, that you want to map to the color aesthetic. So, you should first pivot_longer() the data, to keep them in a column, then you should include it as a variable inside the aes(). Finally, since the color is now a variable, you can set manual values in the corresponding scale.

    library(tidyverse)
    Alabama <- tibble(AlYear = 2010:2015,
                      AlMed = c(300,400,600,650,700,750),
                      AlCorr = c(400,400,450,500,450,450))
    
    Alabama %>%
      pivot_longer(AlMed:AlCorr, names_to = "Spending Type") %>%
      ggplot(aes(x=AlYear, y = value, color= `Spending Type`)) + 
      geom_line() + 
      labs(title='Figure 3: Alabama Social Spending',
           x='Fiscal Year', y= 'Spending (in $100,000') +
      scale_color_manual(values=c("darkred", "steelblue"),
                         labels = c("Medicaid Spending","Correctional Spending"))
    

    Created on 2020-12-09 by the reprex package (v0.3.0)

    Of course, you can do the same thing for the linetype (add it in the aes() call, and add a scale_linetype_manual() at the end).