如何用RStudio(tidyverse)和ggplot2按年份计算平均进球并绘制趋势图
Got it, let's walk through how to turn that messy raw match data into a clean, interpretable yearly average goals trend plot using tidyverse and ggplot2. Here's a step-by-step breakdown:
1. Install & Load Required Packages
First, ensure you have the tidyverse package (which includes both dplyr for data manipulation and ggplot2 for plotting) installed and loaded:
# Install tidyverse if it's not already on your system if (!require(tidyverse)) { install.packages("tidyverse") } # Load the package into your R session library(tidyverse)
2. Calculate Yearly Average Goals
We'll use dplyr functions to group the raw match data by year and compute the average goals per match. We'll also add an optional count of matches per year for context:
# Process the SoccerTeam dataset to get yearly averages yearly_avg_goals <- SoccerTeam %>% # Group data by the year the match was played group_by(YearPlayed) %>% # Calculate average goals (ignore missing values with na.rm = TRUE) summarize( avg_goals = mean(Goals, na.rm = TRUE), num_matches = n() # Optional: track how many matches were played each year ) %>% # Ungroup to avoid unexpected behavior in later steps ungroup()
3. Create the Time Trend Plot
Now use ggplot2 to visualize the yearly average goals. We'll add both a line (to show the overall trend) and points (to highlight individual year values) for clarity:
# Build the plot ggplot(yearly_avg_goals, aes(x = YearPlayed, y = avg_goals)) + # Add a solid line for the trend geom_line(color = "#2c3e50", linewidth = 1) + # Add points to mark each year's average geom_point(size = 2.5, color = "#e74c3c") + # Customize labels and title labs( title = "Yearly Average Goals Scored (1950-2020)", x = "Year", y = "Average Goals Per Match", caption = "Data source: SoccerTeam match records" ) + # Use a clean, minimal theme theme_minimal() + # Tweak text styling for readability theme( plot.title = element_text(hjust = 0.5, size = 14, face = "bold"), axis.title = element_text(size = 12), axis.text = element_text(size = 10) )
Notes for Edge Cases
- If your
YearPlayedcolumn is stored as a character instead of numeric, convert it first withmutate(YearPlayed = as.numeric(YearPlayed))before grouping. - If you want to highlight years with an unusually high/low number of matches, you could map
num_matchesto point size withgeom_point(aes(size = num_matches)).
内容的提问来源于stack exchange,提问作者Kevin

