Home > Software engineering >  How can I add a legend?
How can I add a legend?

Time:03-13

I have a data set that includes the goal (money wise) non profits wants to raise, with the column next to it saying the year of their goal, and then next to it how much they actually collected/raised that year

I did the following to sum how the total of goal amounts per year and to sum the total of money actually collected per year:

total_goal <- aggregate(x = data$goal,by = list(year), FUN = sum)  
total_collected <- aggregate(x = data$collected, by = list(year), FUN = sum)  

Now I want to plot this data. I did it like so:

plot <- ggplot(data = total_collected, aes(x=Group.1, y=x, group=1))  
  geom_line(data = total_goal, aes(x = Group.1, y =x, color = "Total  Goal"))  
  geom_line(data = total_collected, aes(x = Group.1, y =x, color = "Total Collected"), linetype="dotted")  
  geom_point(color = "orange")  
  scale_color_manual(name = "Legend", values = c("Total Goal" = "green", "Total Collected" = "orange"))  
  labs(title = "xx")  
  xlab("xx")  
  ylab("xx") 

As you can see I had to manually add the legend stating:

scale_color_manual(name = "Legend", 
                   values = c("Total Goal" = "green", "Total Collected" = "orange")) 

How can I add this legend without manually writing it like this? So that it derives from the data points itself.

The legend should mark green for Goal and orange for Amount Collected.

Thank you!

Also, maybe there is a simpler way to do this whole plot and i am just over complicating it, any thoughts on a simpler code are welcomed.

CodePudding user response:

First I created some sample data:

total_goal <- data.frame(Group.1 = c(1, 2, 3, 4, 5, 6),
                              x = c(1, 2, 5, 3, 4, 2))

total_collected <- data.frame(Group.1 = c(1, 2, 3, 4, 5, 6),
                              x = c(2, 4, 2, 5, 6, 1))

You can use this code:

plot <- ggplot(data = total_collected, aes(x=Group.1, y=x, group=1))  
  geom_line(data = total_goal, aes(x = Group.1, y =x, color = "Total Goal"))  
  geom_line(data = total_collected, aes(x = Group.1, y =x, color = "Total Collected"), linetype="dotted")  
  geom_point(color = "orange")  
  scale_color_manual(name = "Legend", breaks = c("Total Goal", "Total Collected"), 
                     values = c("Total Goal" = "green", "Total Collected" = "orange"))  
  labs(title = "xx")  
  xlab("xx")  
  ylab("xx") 

plot

Output plot:

enter image description here

  • Related