Search code examples
rggplot2legend-properties

Changing the legend name and variable name in the theme_pander package in R on a line graph


I have been trying to change the legend title on the graph from "Political_Party" to "Political Party" and the variables from "D" and "R" to "Democrat" and "Republican" to no avail in the graph I am making. The code I am using for the graph is reproduced below.

Raw_Plot_Cases <- 
  ggplot(Combined_Averages_Cases, aes(x = date, y = CasesperDay, group = Political_Party, color = Political_Party)) +
  geom_line() 

Raw_Plot_Cases <- Raw_Plot_Cases +
  theme_pander() +
  scale_x_date(date_breaks = "1 month", labels = date_format("%b %d")) +
  scale_color_manual(values=c('#0015BC','#DE0100')) +
  theme(plot.title.position = "plot",
        plot.caption = element_markdown(),
        legend.position = "bottom",
        axis.title.x = element_text(),
        legend.title = element_text("Political Party")) + 
    labs(title = "Average State-Wide Daily Covid-19 Cases",
         subtitle = "By Political Party",
         x = "Date", 
         y = "Daily Cases",
         caption = "Data from *The New York Times*, based on reports from state and local health agencies.")


Solution

  • The theme determines how things (like the legend title) are formatted - it doesn't define the text. Your legend looks to be a color legend. Two good options for setting the name label of the color legend are (a) add color = "Political Party" inside your labs() call where you set all the other text, or (b) put name = "Political Party" inside your scale_color_manual() call.

    Similarly, for changing D to Democrat and R to Republican, there are two good options. One is to change the values in your actual data, the other is to set the labels in scale_color_manual, like this:

    scale_color_manual(
      values = c('#0015BC','#DE0100'),
      breaks = c("D", "R"),
      labels = c("Democrat", "Republican")
    )