使用R ggplot2可视化含重复类别的网球赛事成绩数据
Got it, I know exactly the kind of visualization you're going for—those clean, color-coded year-by-year result charts like you see on Wikipedia for tennis players. Let's work through this step by step:
First, your current factor levels are based on the order Rank first appears in the data, which doesn't reflect the actual hierarchy of tournament results. Let's reorder them from earliest exit to champion so the color mapping makes intuitive sense:
data$Rank <- factor(data$Rank, levels = c("Q1", "3R", "4R", "SF", "F", "W"), ordered = TRUE)
We'll use geom_tile() to create solid color blocks for each year—this is perfect because it's not a bar chart, just a color-coded marker for each year's result. Here's the full code:
library(ggplot2) ggplot(data, aes(x = Year, y = 1, fill = Rank)) + # Create color tiles with white borders to separate years geom_tile(height = 0.8, color = "white") + # Manually assign colors to match standard tennis result conventions scale_fill_manual(values = c( "Q1" = "#cccccc", # Qualifying round: light gray "3R" = "#99ccff", # 3rd round: light blue "4R" = "#3399ff", # 4th round: medium blue "SF" = "#003399", # Semifinal: dark blue "F" = "#ff9933", # Final: orange "W" = "#cc0000" # Winner: red )) + # Ensure every year shows up on the X-axis scale_x_continuous(breaks = 1999:2020, labels = 1999:2020) + # Clean up the theme to match Wikipedia's minimal style theme_minimal() + theme( axis.title.y = element_blank(), # Hide Y-axis label axis.text.y = element_blank(), # Hide Y-axis text axis.ticks.y = element_blank(), # Hide Y-axis ticks panel.grid = element_blank(), # Remove grid lines legend.title = element_text(hjust = 0.5), # Center legend title plot.title = element_text(hjust = 0.5, size = 14, face = "bold") # Center and style title ) + labs( title = "Roger Federer's Annual Tournament Results (1999-2020)", fill = "Tournament Result" )
geom_tile()creates a solid color block for each year. Settingy = 1keeps all blocks in a single row, andheight = 0.8keeps them from touching the top/bottom of the plot area.- The manual color scale uses intuitive hues for each result level—you can tweak these hex codes to match Wikipedia's exact colors if you want.
- The theme adjustments strip out unnecessary elements, making the chart clean and focused on the year-to-year result progression, just like the Wikipedia version.
If you prefer a vertical layout (similar to the table-style view on Wikipedia), just swap x and y in the aes() call, adjust the axis breaks, and tweak the tile width instead of height—super easy to modify!
内容的提问来源于stack exchange,提问作者k.atli

