Missing Legend using geom_line

I'm using the following code to compare two variables using a line chart. However, the legend of the chart is missing.

It may be because while creating another chart in the same file earlier I changed legend.position = "none". But, it I don't know how it got defaulted for all data viz.

Please help. This is my first portfolio project. Thanks!

Hypo1_df <- new_df %>% 
 count(route, route_name, member_casual, sort = T) %>% 
  pivot_wider(names_from = member_casual, values_from = n) %>% 
  mutate(total_rides = casual + member, casual_perc = round(casual/total_rides*100, digits = 2), member_perc = 100 - casual_perc) %>%
  filter(total_rides >= 3000) 

ggplot(data = Hypo1_df, mapping = aes(x = route)) + 
  geom_line(mapping = aes(y = casual_perc), group = 1, color = "red", size = 1.5) +
  geom_line(mapping = aes(y = member_perc), group = 1, color = "blue", size = 1.5) +

  theme(axis.text.x = element_text(angle = 90),  legend.position = "right") +

  labs(title = "Comparison: Casual and Member riders", 
  subtitle = "Only considers the top routes (i.e. having more than 3000 rides per year)", 
  x = "Route", y = "% Rides\n(out of total riders on the station)")

If you manually set values for each line instead of mapping a grouping variable to the colour aesthetic, you have to also manually define the legend.

If you need more specific help, please provide a proper REPRoducible EXample (reprex) illustrating your issue.

A bit off topic, but is a line chart really the best chart for that dataset? They're good for time series. Not necessarily for what you are showing.

For your chart, you could have the colour based on a column within the aes() bit in the geom_line() then use scale_colour_manual() to set the colours.

1 Like

Thanks William for your input. Yes, this representation could be misleading as a line chart.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.