Search code examples
rggplot2visualizationlegenddata-analysis

Changing Title of Legend in ggplot2 Creates a Second Legend?


I am pretty new to R/working with data and am trying to change the title of the legend in a visualization I made. I have tried using fill= in the labels() function I have but it adds another legend for some reason. I have looked around for a solution and found this post however neither solution solved my problem.

Here is my code as I had it originally along with the visualization it makes:

data_2023_2 %>% 
  group_by(rideable_type, member_type) %>%
  dplyr::summarize(total_trips = n()) %>% 
  ggplot(aes(x=rideable_type, y=total_trips, fill=member_type, color=member_type)) +
  geom_bar(stat='identity', position = position_dodge2(preserve = "single", padding = 0.1)) +
  geom_text(aes(label = total_trips), position = position_dodge2(preserve = "single", width = 0.9, padding = 0.1), vjust=1.5, colour="white") +
  scale_fill_manual(values=c("darkorchid","darkseagreen")) +
  scale_color_manual(values=c("darkorchid","darkseagreen")) +
  theme_bw()+
  labs(title="Number of Trips by Bike Type", x="Bicycle Type", y="Number of Rides")

Viz With Bad Legend Title

And then here is the code with fill= added in

data_2023_2 %>% 
  group_by(rideable_type, member_type) %>%
  dplyr::summarize(total_trips = n()) %>% 
  ggplot(aes(x=rideable_type, y=total_trips, fill=member_type, color=member_type)) +
  geom_bar(stat='identity', position = position_dodge2(preserve = "single", padding = 0.1)) +
  geom_text(aes(label = total_trips), position = position_dodge2(preserve = "single", width = 0.9, padding = 0.1), vjust=1.5, colour="white") +
  scale_fill_manual(values=c("darkorchid","darkseagreen")) +
  scale_color_manual(values=c("darkorchid","darkseagreen")) +
  theme_bw()+
  labs(title="Number of Trips by Bike Type", x="Bicycle Type", y="Number of Rides", fill="Member Type")

Viz With 2 Legends But One of Them Has The Good Title I Want


Solution

  • you can do that in the labs function like this:

    data_2023_2 %>% 
      group_by(rideable_type, member_type) %>%
      dplyr::summarize(total_trips = n()) %>% 
      ggplot(aes(x=rideable_type, y=total_trips, fill=member_type)) +
      geom_bar(stat='identity', position = position_dodge2(preserve = "single", padding = 0.1)) +
      geom_text(aes(label = total_trips, fill = member_type), position = position_dodge2(preserve = "single", width = 0.9, padding = 0.1), vjust=1.5, colour="white") +
      scale_fill_manual(values=c("darkorchid","darkseagreen")) +
      theme_bw() +
      labs(title="Number of Trips by Bike Type", x="Bicycle Type", y="Number of Rides", fill="Member Type")