如何为数据集各值生成独立数据集?求解释R语言gridExtra绘图脚本
Hey there! Let's break down your provided code piece by piece, fix a small bug in it, and then show you straightforward ways to create individual plots for each of your 21 genes.
原代码的详细解释
First, let's walk through what each part does:
Load required packages
library(ggplot2): This is the go-to package for creating polished, customizable plots in R.library(gridExtra): The star here is itsgrid.arrange()function, which lets you combine multiple ggplot objects into a single layout (great for putting all your gene plots on one page or PDF).
Prepare the data
data=read.csv("tubgal4crosses.csv"): Reads your CSV dataset into R.str(data): Prints the structure of your data (variable types, sample values) to help you verify it loaded correctly.datasum=aggregate(Count~Gene+Sex+Markers,FUN=sum,data=data): Aggregates your data by grouping onGene,Sex, andMarkers, then sums up theCountvalues. This ensures you're plotting total counts per group instead of raw, possibly duplicated data.genes=unique(data$Gene): Extracts all distinct gene names from your dataset—this is what we'll loop over to create a plot for each gene.
The plot list (
p) and loopp<-list(): Initializes an empty list to store each ggplot object. Using a list is perfect here because we need to hold multiple plot objects (one per gene) to combine later.- The
whileloop runs once for each gene:p[[i]]<-ggplot(...): Creates a grouped bar plot for the i-th gene. We filter the aggregated data to only include the current gene, setx=Markers,y=Count, and usefill=Sexto color-code bars by sex.geom_bar(stat="identity", position=position_dodge())makes grouped bars (side-by-side instead of stacked), andtheme_minimal()applies a clean, simple theme.- Important bug fix: Your original code has two lines (
p[[i]] + scale_fill_manual(...)andp[[i]] + ggtitle(genes[i])) that don't actually modify the plot stored inp[[i]]. You need to reassign these changes back top[[i]], like this:
Without this reassigning, the custom colors and gene title won't show up in your final plots!p[[i]] <- p[[i]] + scale_fill_manual(values=c('#999999','#E69F00')) p[[i]] <- p[[i]] + ggtitle(genes[i])
Save all plots to a single PDF
pdf("scop.pdf"): Opens a PDF file to save your plots.do.call(grid.arrange,p): Usesgrid.arrange()to arrange all plots in the listpinto a single layout (it automatically decides how many rows/columns to use based on the number of plots).do.call()is needed here becausegrid.arrange()doesn't accept a list directly—this function passes each plot in the list as a separate argument togrid.arrange().dev.off(): Closes the PDF device, finalizing your saved file.
拆分绘制独立图表的方法
If you want each gene's plot saved as a separate file (or as separate pages in a PDF), here are two easy approaches:
Method 1: Save each plot as an individual file (PDF/PNG)
This uses ggsave() (ggplot's built-in save function) to create a unique file for each gene:
library(ggplot2) # Load and prepare data data <- read.csv("tubgal4crosses.csv") datasum <- aggregate(Count~Gene+Sex+Markers, FUN=sum, data=data) genes <- unique(data$Gene) # Loop through each gene to create and save a plot for (gene in genes) { # Create the plot for the current gene plot <- ggplot(data=subset(datasum, Gene==gene), aes(x=Markers, y=Count, fill=Sex)) + geom_bar(stat="identity", position=position_dodge()) + theme_minimal() + scale_fill_manual(values=c('#999999','#E69F00')) + ggtitle(gene) # Save as PDF (change extension to .png for image files) ggsave( filename = paste0(gene, ".pdf"), # Filename uses the gene name plot = plot, width = 6, # Adjust width/height as needed height = 4 ) }
This will generate files like GeneX.pdf, GeneY.pdf, etc., each containing only the plot for that gene.
Method 2: Save all plots as separate pages in one PDF
If you prefer having all plots in a single PDF but on separate pages (instead of a grid), use this approach:
library(ggplot2) library(gridExtra) # Load and prepare data data <- read.csv("tubgal4crosses.csv") datasum <- aggregate(Count~Gene+Sex+Markers, FUN=sum, data=data) genes <- unique(data$Gene) # Open a PDF file that will hold all plots (one per page) pdf("scop_individual_pages.pdf", onefile = TRUE) # Loop through each gene and add its plot to the PDF for (gene in genes) { plot <- ggplot(data=subset(datasum, Gene==gene), aes(x=Markers, y=Count, fill=Sex)) + geom_bar(stat="identity", position=position_dodge()) + theme_minimal() + scale_fill_manual(values=c('#999999','#E69F00')) + ggtitle(gene) grid.arrange(plot) # Adds the plot as a new page } dev.off() # Close the PDF device
The onefile = TRUE argument ensures all plots are saved to the same PDF, each on its own page.
内容的提问来源于stack exchange,提问作者Kodewings

