R语言ggplot绘制多折线图:图例消失等问题求助
Hey there! Let's fix those issues one by one and get your plot looking exactly how you want it. The main pain point with your original code is using wide-format data—ggplot works much smoother with long-format data when dealing with multiple lines and legends. Here's a step-by-step solution:
Step 1: Reshape Your Data & Prep Dates
First, we'll convert your wide data to long format (so we can group lines by category) and turn your x column into proper dates (this makes handling year labels way easier):
library(ggplot2) library(tidyr) # Convert wide data to long format data_long <- data %>% pivot_longer(cols = starts_with("y."), names_to = "category", values_to = "count") %>% # Clean up category names (remove the "y." prefix) mutate(category = gsub("y\\.", "", category)) # Convert x to date format (add "-01" to make valid dates) data_long$x <- as.Date(paste0(data_long$x, "-01"))
Step 2: Build the Fixed Plot
This code addresses all three of your issues:
ggplot(data = data_long, aes(x = x, y = count, color = category, shape = category)) + # Add lines and points, grouped by category geom_line(linewidth = 1) + geom_point(size = 2) + # Add vertical event lines (now using actual dates instead of index positions) geom_vline(xintercept = as.Date("2013-07-01"), linetype = "longdash", color = "gray50") + geom_vline(xintercept = as.Date("2014-07-01"), linetype = "longdash", color = "gray50") + # Plot labels labs(title = "Media Attention", x = "", y = "Media Articles") + # Customize colors and shapes for each category scale_color_manual(values = c("articles" = "darkblue", "police" = "darkred", "protester" = "darkgreen")) + scale_shape_manual(values = c("articles" = 16, "police" = 17, "protester" = 15)) + # Set X-axis to only show year labels scale_x_date(breaks = as.Date(c("2013-01-01", "2014-01-01", "2015-01-01", "2016-01-01")), labels = c("2013", "2014", "2015", "2016")) + # Theme adjustments theme(plot.title = element_text(hjust = 0.5, face = "bold"), legend.position = "bottom", legend.title = element_blank(), axis.text.x = element_text(vjust = 0.5))
What This Fixes:
- Missing Legend: By mapping
colorandshapeto thecategorycolumn in long-format data, ggplot automatically generates a legend. Your original code added lines individually without grouping, so no legend was created. - Different Shape Markers: The
scale_shape_manuallet's you assign distinct shapes (16 = solid circle, 17 = solid triangle, 15 = solid square—adjust these values if you prefer other shapes). - Year-Only X-Labels: Converting
xto dates lets us usescale_x_dateto set breaks at the start of each year, with labels showing only the year. We also updated the vertical line positions to use actual dates instead of row indices, so they align correctly with your timeline.
内容的提问来源于stack exchange,提问作者maneesh
相关产品推荐
相关产品推荐

