如何用ggplot2绘制多数据集折线图并保存为PDF(带图例)
Got it, let's convert your base R plot to a clean ggplot2 version with proper legends and save it as a PDF. The key here is reshaping your wide-format matrices into tidy long-format data, which plays nicely with ggplot's grammar.
First, here's the complete code with explanations:
# Load required library library(tidyverse) # Generate your original data (added set.seed for reproducibility) set.seed(123) mean <- replicate(10, rnorm(10)) colnames(mean) <- paste0(rep(c("x0","x1","x2","x3","x4"),2),"_c", rep(c(1:2), each=5)) meanpos <- replicate(10, rnorm(10)) + 1.5 meanneg <- replicate(10, rnorm(10)) - 1.5 hcol <- c(0,0.5,0,0.75,1.0, 1.1,1.20,0,0.8,-0.025) # Reshape data to long format (required for ggplot) # Convert each matrix to a tidy data frame with group labels mean_df <- as.data.frame(mean) %>% mutate(sl_no = 1:n()) %>% pivot_longer(-sl_no, names_to = "Variable", values_to = "Value") %>% mutate(Group = "Mean") meanpos_df <- as.data.frame(meanpos) %>% mutate(sl_no = 1:n()) %>% pivot_longer(-sl_no, names_to = "Variable", values_to = "Value") %>% mutate(Group = "Mean + 1.5") meanneg_df <- as.data.frame(meanneg) %>% mutate(sl_no = 1:n()) %>% pivot_longer(-sl_no, names_to = "Variable", values_to = "Value") %>% mutate(Group = "Mean - 1.5") # Combine all data frames into one combined_data <- bind_rows(mean_df, meanpos_df, meanneg_df) # Create a separate data frame for the horizontal reference lines hline_data <- tibble(Variable = colnames(mean), hcol = hcol) # Build the ggplot plot <- ggplot(combined_data, aes(x = sl_no, y = Value, color = Group)) + # Add the three line series geom_line(linewidth = 1) + # Add purple horizontal reference lines per facet geom_hline(data = hline_data, aes(yintercept = hcol), color = "purple", linetype = "dashed") + # Arrange facets in 2 rows and 5 columns (fits all 10 variables perfectly) facet_wrap(~ Variable, nrow = 2, ncol = 5) + # Customize labels and title labs(x = "sl no", y = "Value", title = "Line Plots with Mean, Mean ±1.5 and Reference Lines") + # Set custom colors matching your original plot scale_color_manual(values = c("Mean" = "black", "Mean + 1.5" = "blue", "Mean - 1.5" = "green")) + # Use a clean theme theme_bw() + # Adjust theme elements for readability theme( plot.title = element_text(hjust = 0.5), # Center the plot title legend.position = "bottom", # Move legend to bottom for better space axis.text = element_text(size = 8), # Shrink axis text to fit facets strip.text = element_text(size = 8) # Shrink facet labels ) # Save the plot as a PDF ggsave("line_plots.pdf", plot, width = 12, height = 6, dpi = 300)
Key Notes:
- Tidy Data: We converted each wide matrix into a long-format data frame with
pivot_longer, which lets ggplot easily map groups to colors. - Faceting:
facet_wrapwithnrow=2andncol=5arranges all 10 variable plots into a neat grid (your original mention of 2x2 might have been a typo, but if you really want 2x2, you can adjust thenrow/ncolvalues—though it will only show 4 plots at a time). - Legends: The
color=Groupaesthetic automatically creates a legend, which we customized withscale_color_manualto match your original line colors. - Saving:
ggsavelets you specify the output file, dimensions, and resolution. Adjustwidthandheightas needed for your preferred layout.
This code will produce a PDF with all 10 subplots, each showing the three line series and the purple reference line, plus a clear legend at the bottom.
内容的提问来源于stack exchange,提问作者MNU
相关产品推荐
相关产品推荐

