Search code examples
rggplot2geom-point

Grouping and colouring with ggplot at the same time


I've got two teams and a given value for each team and year for a certain time interval. My data looks like the following:

yearID teamID value
2020 0 5
2020 1 7
2019 0 3
2019 1 1

I want to plot this with a point for each year and value, distunguishing between teams by color. Additionally I want to draw lines between points grouped by year. I am almost there:

ggplot(hr_by_team_year_sf_la_df, aes(x='yearID', y='HR', group='yearID')) + geom_line() + geom_point()

resulting in the following plot:

enter image description here

Only colors miss for now. I've tried several approaches but none succeeded:

  1. ggplot(hr_by_team_year_sf_la_df, aes(x='yearID', y='HR', group='yearID')) + geom_line() + geom_point(aes(color='teamID'))
  2. ggplot(hr_by_team_year_sf_la_df, aes(x='yearID', y='HR', group='yearID', color='teamID')) + geom_line() + geom_point()

Anyone got an idea how to paint the points depending on the teamId?


Solution

  • Do you mean something like this?

    library(tidyverse)
    
    df <- tibble(yearID = c("2020","2020","2019","2019"), 
                 teamID = c(0, 1, 0, 1), 
                 value = c(5, 7, 3, 1)) %>% 
      mutate(teamID = as.factor(teamID))
    
    ggplot(df) + 
      geom_line(aes(yearID, value)) + 
      geom_point(aes(yearID, value, color = teamID), size = 3)
    

    enter image description here