| Title: | ChIPseeker for ChIP peak Annotation, Comparison, and Visualization |
|---|---|
| Description: | This package implements functions to retrieve the nearest genes around the peak, annotate genomic region of the peak, statstical methods for estimate the significance of overlap among ChIP peak data sets, and incorporate GEO database for user to compare the own dataset with those deposited in database. The comparison can be used to infer cooperative regulation and thus can be used to generate hypotheses. Several visualization functions are implemented to summarize the coverage of the peak experiment, average profile and heatmap of peaks binding to TSS regions, genomic annotation, distance to TSS, and overlap of peaks or genes. |
| Authors: | Guangchuang Yu [aut, cre] (ORCID: <https://orcid.org/0000-0002-6485-8781>), Ming Li [ctb], Qianwen Wang [ctb], Yun Yan [ctb], Hervé Pagès [ctb], Michael Kluge [ctb], Thomas Schwarzl [ctb], Zhougeng Xu [ctb], Chun-Hui Gao [ctb] (ORCID: <https://orcid.org/0000-0002-1445-7939>) |
| Maintainer: | Guangchuang Yu <[email protected]> |
| License: | Artistic-2.0 |
| Version: | 1.49.5 |
| Built: | 2026-11-12 08:37:45 UTC |
| Source: | https://github.com/bioc/ChIPseeker |
ChIPseeker is an R/Bioconductor package designed for comprehensive analysis of ChIP-seq (Chromatin Immunoprecipitation followed by sequencing) data. The package provides a complete toolkit for annotating ChIP peaks, comparing datasets, and visualizing results to facilitate biological interpretation.
ChIPseeker offers four main categories of functionality:
1. Peak Annotation:
annotatePeak: Comprehensive peak annotation including
nearest genes, genomic features (promoter, exon, intron, UTR, etc.),
distance to TSS, and optional gene annotation from databases
seq2gene: Many-to-many mapping of genomic regions to
genes for functional enrichment analysis, considering host genes,
promoter regions, and flanking genes
readPeakFile: Read peak files in various formats
(BED, narrowPeak, broadPeak, etc.)
2. Visualization:
plotAnnoBar, plotAnnoPie: Visualize
genomic annotation distribution
plotDistToTSS: Distribution of peaks relative to
transcription start sites
covplot: Coverage plot showing peak distribution
across chromosomes
plotAvgProf, plotPeakProf: Average
profiles and peak profiles around TSS or gene body
tagHeatmap, peakHeatmap: Heatmaps of
peak binding patterns
vennplot, upsetplot: Visualize overlap
among multiple peak sets
3. Peak Comparison and Overlap Analysis:
enrichAnnoOverlap: Test significance of gene overlap
between ChIP experiments based on nearest gene annotation
enrichPeakOverlap: Test significance of genomic
coordinate overlap using permutation testing
shuffle: Shuffle peak positions for permutation testing
4. GEO Database Integration:
downloadGEObedFiles, downloadGSMbedFiles:
Download ChIP-seq data from GEO database
getGEOInfo, getGEOspecies,
getGEOgenomeVersion: Query GEO database metadata
Access to over 17,000 ChIP-seq datasets from GEO for comparison
Additional Features:
getTagMatrix: Build tag matrices for profile plotting
getPromoters: Extract promoter regions
getBioRegion: Define custom genomic regions
dplyr verb extensions for GRanges objects: filter,
mutate, rename, arrange
Support for liftOver conversion between genome assemblies
The typical ChIPseeker workflow:
Read peak files using readPeakFile
Annotate peaks using annotatePeak to get nearest genes,
genomic features, and distances
Visualize results using plotAnnoBar,
plotDistToTSS, etc.
(Optional) Compare with other datasets using enrichPeakOverlap
or download from GEO
(Optional) Map regions to genes using seq2gene for
functional enrichment analysis
csAnno-class: Container class for annotated peaks
with metadata and statistics
If you use ChIPseeker in published research, please cite:
Q Wang, M Li, T Wu, L Zhan, L Li, M Chen, W Xie, Z Xie, E Hu, S Xu, G Yu. Exploring epigenomic datasets by ChIPseeker. Current Protocols, 2022, 2(10): e585.
G Yu, LG Wang, QY He. ChIPseeker: an R/Bioconductor package for ChIP peak annotation, comparison and visualization. Bioinformatics, 2015, 31(14):2382-2383.
Maintainer: Guangchuang Yu [email protected]
Contributors: Ming Li, Qianwen Wang, Yun Yan, Hervé Pagès, Michael Kluge, Thomas Schwarzl, Zhougeng Xu, Chun-Hui Gao
Useful links:
Report bugs at https://github.com/YuLab-SMU/ChIPseeker/issues
Bioconductor page: https://bioconductor.org/packages/ChIPseeker
capture name of variable
.(..., .env = parent.frame()).(..., .env = parent.frame())
... |
expression |
.env |
environment |
expression
x <- 1 eval(.(x)[[1]])x <- 1 eval(.(x)[[1]])
The function initializes and maintains a cache for TxDb objects and their associated genomic features. It checks if the cached TxDb matches the provided one, and updates the cache if they differ or if forced to update.
.ChIPseekerEnv(TxDb, item = "ChIPseekerEnv", force = FALSE).ChIPseekerEnv(TxDb, item = "ChIPseekerEnv", force = FALSE)
TxDb |
TxDb or EnsDb annotation object to cache |
item |
character, name of the cache item. Default is "ChIPseekerEnv" |
force |
logical, whether to force update of the TxDb in cache, clearing all cached features. Default is FALSE |
This function manages the caching system for TxDb objects and related genomic features to improve performance by avoiding redundant computations.
The function performs the following:
Retrieves or creates a cache item
If no TxDb is cached, stores the provided TxDb
If a TxDb exists in cache, compares metadata to check if it matches
Updates cache if TxDb differs or if force=TRUE
Prints the genome version being used
This caching mechanism allows the package to reuse computed features (exons, introns, transcripts, etc.) across multiple function calls when using the same TxDb object.
Invisibly returns NULL. Prints messages about genome version usage
This function annotates ChIP-seq peaks with genomic features including nearest genes, genomic annotation (promoter, exon, intron, etc.), distance to TSS, and optional gene annotation from annotation databases. It can also identify flanking genes within a specified distance from peaks.
annotatePeak( peak, tssRegion = c(-3000, 3000), TxDb = NULL, level = "transcript", assignGenomicAnnotation = TRUE, genomicAnnotationPriority = c("Promoter", "5UTR", "3UTR", "Exon", "Intron", "Downstream", "Intergenic"), annoDb = NULL, addFlankGeneInfo = FALSE, flankDistance = 5000, sameStrand = FALSE, ignoreOverlap = FALSE, ignoreUpstream = FALSE, ignoreDownstream = FALSE, overlap = "TSS", verbose = TRUE, columns = c("ENTREZID", "ENSEMBL", "SYMBOL", "GENENAME") )annotatePeak( peak, tssRegion = c(-3000, 3000), TxDb = NULL, level = "transcript", assignGenomicAnnotation = TRUE, genomicAnnotationPriority = c("Promoter", "5UTR", "3UTR", "Exon", "Intron", "Downstream", "Intergenic"), annoDb = NULL, addFlankGeneInfo = FALSE, flankDistance = 5000, sameStrand = FALSE, ignoreOverlap = FALSE, ignoreUpstream = FALSE, ignoreDownstream = FALSE, overlap = "TSS", verbose = TRUE, columns = c("ENTREZID", "ENSEMBL", "SYMBOL", "GENENAME") )
peak |
peak file (BED, narrowPeak, broadPeak, etc.) or GRanges object containing genomic ranges of peaks to be annotated |
tssRegion |
numeric vector of length 2 specifying the range of TSS region for promoter annotation. Default is c(-3000, 3000), meaning 3kb upstream and 3kb downstream of TSS. Negative values indicate upstream, positive values indicate downstream |
TxDb |
TxDb or EnsDb annotation object, or a GRanges object containing user-defined genomic features. If a GRanges object is provided, some annotation features (genomic annotation, gene annotation, flanking genes) will be disabled |
level |
character, one of "transcript" or "gene". Determines whether to annotate peaks at the transcript level or gene level. Default is "transcript" |
assignGenomicAnnotation |
logical, whether to assign genomic feature categories (Promoter, Exon, UTR, Intron, etc.) to peaks. Default is TRUE |
genomicAnnotationPriority |
character vector specifying the priority order of genomic annotations when a peak overlaps multiple features. Must be a permutation of c("Promoter", "5UTR", "3UTR", "Exon", "Intron", "Downstream", "Intergenic"). Default prioritizes Promoter > 5UTR > 3UTR > Exon > Intron > Downstream > Intergenic |
annoDb |
character, name of annotation database package (e.g., "org.Hs.eg.db") to add gene identifiers (ENSEMBL, SYMBOL, GENENAME, ENTREZID). If NULL, only gene IDs from TxDb will be included. Default is NULL |
addFlankGeneInfo |
logical, whether to identify and include all flanking genes within the specified distance from each peak. If TRUE, adds flank_geneIds and flank_gene_distances columns. Default is FALSE |
flankDistance |
numeric, distance (in base pairs) to extend on both sides of each peak when searching for flanking genes. Only used when addFlankGeneInfo=TRUE. Default is 5000 |
sameStrand |
logical, whether to only consider genes/transcripts on the same strand as the peak when finding nearest features. If FALSE, searches both strands. Default is FALSE |
ignoreOverlap |
logical, whether to ignore overlaps between peaks and TSS/features when finding the nearest gene. If FALSE, overlapping features will be prioritized. Default is FALSE |
ignoreUpstream |
logical, if TRUE, only annotate genes at the 3' end (downstream) of the peak. This restricts annotation to genes that come after the peak. Default is FALSE |
ignoreDownstream |
logical, if TRUE, only annotate genes at the 5' end (upstream) of the peak. This restricts annotation to genes that come before the peak. Default is FALSE |
overlap |
character, one of "TSS" or "all". Determines how overlaps are detected: "TSS" only considers overlaps with the TSS point (transcription start site), while "all" considers overlaps with any part of the gene/transcript body. When overlap="all", any gene overlapping the peak will be reported as the nearest gene, regardless of whether the overlap is at the TSS region. Default is "TSS" |
verbose |
logical, whether to print progress messages during annotation. Default is TRUE |
columns |
character vector, names of columns to retrieve from the annotation database specified by annoDb. Common values include "ENTREZID", "ENSEMBL", "SYMBOL", "GENENAME". Default is c("ENTREZID", "ENSEMBL", "SYMBOL", "GENENAME") |
The function performs comprehensive peak annotation through several steps:
1. **Feature extraction**: Extracts gene or transcript features from the provided TxDb or EnsDb annotation object, or uses user-defined GRanges.
2. **Nearest feature identification**: Finds the nearest gene/transcript to
each peak using getNearestFeatureIndicesAndDistances, considering
strand specificity and overlap options. The overlap parameter
controls whether to consider overlaps with the entire gene body ("all")
or only TSS regions ("TSS").
3. **Distance calculation**: Computes the distance from each peak to the transcription start site (TSS) of the nearest feature, with positive values indicating downstream and negative values indicating upstream.
4. **Genomic annotation**: Assigns genomic feature categories (Promoter-TSS,
5' UTR, 3' UTR, Exon, Intron, Downstream, Intergenic) based on the peak's
location relative to gene structure. The priority order can be customized
via genomicAnnotationPriority.
5. **Gene annotation**: Optionally adds gene identifiers (ENSEMBL, SYMBOL,
GENENAME, ENTREZID) from annotation databases using the annoDb
parameter.
6. **Flanking gene information**: Optionally identifies all genes within a specified flanking distance from each peak, providing comprehensive information about nearby genes.
The function returns a csAnno object containing the annotated peaks
with all metadata columns. When TxDb is provided as a GRanges object,
some features (genomic annotation, gene annotation, flanking genes) are
disabled, and the function works with user-defined genomic features.
A csAnno object containing the annotated peaks. The main
annotation data is stored in the anno slot (a GRanges object) with
the following metadata columns:
All original columns from the input peak file/GRanges object
annotation: Genomic feature category of the peak. Possible
values are Promoter-TSS, 5' UTR, 3' UTR, Exon, Intron, Downstream, and
Intergenic. Only present if assignGenomicAnnotation=TRUE
geneChr: Chromosome of the nearest gene/transcript
geneStart: Start position of the nearest gene/transcript
geneEnd: End position of the nearest gene/transcript
geneLength: Length of the nearest gene/transcript
geneStrand: Strand of the nearest gene/transcript ("+" or "-")
geneId: Gene identifier (Entrez ID for TxDb, or gene_id for EnsDb)
transcriptId: Transcript identifier (only when level="transcript")
distanceToTSS: Distance from peak to the transcription start site
(TSS) of the nearest gene. Positive values indicate downstream, negative
values indicate upstream. Distance is 0 for overlapping peaks
ENSEMBL: Ensembl gene ID (only if annoDb is provided)
SYMBOL: Gene symbol (only if annoDb is provided)
GENENAME: Full gene name (only if annoDb is provided)
ENTREZID: Entrez gene ID (only if annoDb is provided and
requested in columns)
flank_geneIds: Semicolon-separated list of all flanking gene IDs
within the specified distance (only if addFlankGeneInfo=TRUE)
flank_gene_distances: Semicolon-separated list of distances
from the peak to each flanking gene. A distance of 0 means that the
peak overlaps the feature range; at level="transcript" the
feature is the whole transcript, so peaks inside a transcript body
get 0 even when their distance to the TSS is not 0. For
non-overlapping peaks the signed distance to the feature's TSS is
reported (positive = downstream, negative = upstream)
flank_txIds: Semicolon-separated list of all flanking transcript
IDs (only if addFlankGeneInfo=TRUE and level="transcript")
The csAnno object also contains slots for:
tssRegion: The TSS region used for annotation
level: The annotation level ("transcript" or "gene")
hasGenomicAnnotation: Whether genomic annotation was assigned
detailGenomicAnnotation: Detailed annotation matrix (if available)
annoStat: Annotation statistics
peakNum: Total number of peaks
G Yu
plotAnnoBar plotAnnoPie plotDistToTSS
## Not run: require(TxDb.Hsapiens.UCSC.hg19.knownGene) txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene peakfile <- system.file("extdata", "sample_peaks.txt", package="ChIPseeker") peakAnno <- annotatePeak(peakfile, tssRegion=c(-3000, 3000), TxDb=txdb) peakAnno ## End(Not run)## Not run: require(TxDb.Hsapiens.UCSC.hg19.knownGene) txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene peakfile <- system.file("extdata", "sample_peaks.txt", package="ChIPseeker") peakAnno <- annotatePeak(peakfile, tssRegion=c(-3000, 3000), TxDb=txdb) peakAnno ## End(Not run)
The function sorts GRanges objects by converting them to a data.frame, applying the dplyr arrange operation, and converting back to GRanges. This allows sorting by any metadata column or standard GRanges columns (seqnames, start, end, width, strand).
## S3 method for class 'GRanges' arrange(.data, ..., .by_group = FALSE)## S3 method for class 'GRanges' arrange(.data, ..., .by_group = FALSE)
.data |
GRanges object to arrange |
... |
column names or expressions to sort by. Multiple columns can be
specified, with earlier columns taking precedence. Use |
.by_group |
logical, if TRUE, will sort first by grouping variable (if the data is grouped). Currently not used but included for API consistency. Default is FALSE |
This function extends dplyr::arrange() to work with GRanges objects,
allowing users to sort genomic ranges by any column using familiar dplyr
syntax while preserving the GRanges structure.
The function performs the following steps:
Converts GRanges to data.frame using as.data.frame()
Applies dplyr::arrange() with the specified sorting columns
Converts back to GRanges using makeGRangesFromDataFrame()
with keep.extra.columns=TRUE
All genomic range information and metadata columns are preserved. Sorting is stable (preserves original order for ties). Multiple sorting columns are applied in order (first column is primary sort key).
GRanges object with ranges sorted by the specified columns. All metadata columns are preserved. The sort order is stable (ties preserve original order)
## Not run: ## Sort by chromosome and start position (genomic order) peak.gr <- peak.gr %>% arrange(seqnames, start) ## Sort by distance (descending - closest to TSS first) peak.gr <- peak.gr %>% arrange(desc(abs(distanceToTSS))) ## Sort by annotation, then by distance peak.gr <- peak.gr %>% arrange(annotation, distanceToTSS) ## Sort by score (descending), then by chromosome peak.gr <- peak.gr %>% arrange(desc(score), seqnames) ## Complex sorting with multiple criteria peak.gr <- peak.gr %>% arrange( annotation, desc(score), abs(distanceToTSS) ) ## End(Not run)## Not run: ## Sort by chromosome and start position (genomic order) peak.gr <- peak.gr %>% arrange(seqnames, start) ## Sort by distance (descending - closest to TSS first) peak.gr <- peak.gr %>% arrange(desc(abs(distanceToTSS))) ## Sort by annotation, then by distance peak.gr <- peak.gr %>% arrange(annotation, distanceToTSS) ## Sort by score (descending), then by chromosome peak.gr <- peak.gr %>% arrange(desc(score), seqnames) ## Complex sorting with multiple criteria peak.gr <- peak.gr %>% arrange( annotation, desc(score), abs(distanceToTSS) ) ## End(Not run)
The function converts the anno slot (GRanges object) to a data.frame,
preserving all metadata columns. This is useful for exporting data,
performing data.frame operations, or using with functions that require
data.frame input.
## S3 method for class 'csAnno' as.data.frame(x, row.names = NULL, optional = FALSE, ...)## S3 method for class 'csAnno' as.data.frame(x, row.names = NULL, optional = FALSE, ...)
x |
|
row.names |
character vector or NULL, row names for the resulting data.frame. If NULL, default row names are used. Default is NULL |
optional |
logical, kept for compatibility with generic method but should be omitted. Default is FALSE |
... |
additional parameters (currently unused) |
This function converts a csAnno object to a data.frame by extracting
and converting the GRanges object containing annotated peaks.
A data.frame containing all peak information with columns:
Standard GRanges columns: seqnames, start, end, width, strand
All metadata columns: annotation, geneId, distanceToTSS, geneChr, geneStart, geneEnd, etc.
Guangchuang Yu https://guangchuangyu.github.io
as.GRanges for converting to GRanges object
## Not run: peak.df <- as.data.frame(peakAnno) ## Export to CSV write.csv(peak.df, "annotated_peaks.csv") ## End(Not run)## Not run: peak.df <- as.data.frame(peakAnno) ## Export to CSV write.csv(peak.df, "annotated_peaks.csv") ## End(Not run)
The function returns the anno slot from the csAnno object,
which contains all annotated peaks as a GRanges object with metadata columns
(annotation, geneId, distanceToTSS, etc.).
as.GRanges(x)as.GRanges(x)
x |
|
This function extracts the GRanges object containing annotated peaks from a
csAnno object.
GRanges object containing all annotated peaks with their metadata
columns. This is the same as accessing x@anno directly
Guangchuang Yu https://guangchuangyu.github.io
## Not run: peak.gr <- as.GRanges(peakAnno) ## Equivalent to: peak.gr <- peakAnno@anno ## End(Not run)## Not run: peak.gr <- as.GRanges(peakAnno) ## Equivalent to: peak.gr <- peakAnno@anno ## End(Not run)
The function merges multiple csAnno objects that were created with
the same annotation parameters (TSS region, level, genomic annotation status).
It combines all peaks, merges annotation statistics, and creates a unified
summary. This is useful for comparing or combining results from multiple
ChIP-seq experiments.
combine_csAnno(x, ...)combine_csAnno(x, ...)
x |
|
... |
additional |
This function combines two or more csAnno objects into a single
object, merging their peaks and aggregating annotation statistics.
The function performs the following operations:
Validates that all objects are csAnno instances
Checks that all objects have the same tssRegion, level,
and hasGenomicAnnotation values
Combines all GRanges objects from the anno slots
Merges detailGenomicAnnotation data frames by row binding
Aggregates annotation statistics by merging and summing frequencies across all objects
Sums the total peak counts
The resulting object contains all peaks from all input objects with combined annotation statistics showing the overall distribution across genomic features.
A new csAnno object containing:
All peaks from all input objects combined
Merged annotation statistics with aggregated frequencies
Combined detail genomic annotations
Sum of peak counts from all objects
The tssRegion, level, and hasGenomicAnnotation are
inherited from the first object (all must be identical)
Guangchuang Yu https://guangchuangyu.github.io
https://github.com/YuLab-SMU/ChIPseeker/issues/157
annotatePeak for creating csAnno objects
## Not run: ## Combine two peak annotation results combined <- combine_csAnno(peakAnno1, peakAnno2, peakAnno3) ## Visualize combined statistics plotAnnoBar(combined) ## End(Not run)## Not run: ## Combine two peak annotation results combined <- combine_csAnno(peakAnno1, peakAnno2, peakAnno3) ## Visualize combined statistics plotAnnoBar(combined) ## End(Not run)
The function creates a coverage plot showing where peaks are located across chromosomes. It calculates coverage by counting overlapping peaks at each genomic position, and displays the results as a bar/rectangular plot with one panel per chromosome.
covplot( peak, weightCol = NULL, xlab = "Chromosome Size (bp)", ylab = "", title = "ChIP Peaks over Chromosomes", chrs = NULL, xlim = NULL, lower = 1, fill_color = "black" )covplot( peak, weightCol = NULL, xlab = "Chromosome Size (bp)", ylab = "", title = "ChIP Peaks over Chromosomes", chrs = NULL, xlim = NULL, lower = 1, fill_color = "black" )
peak |
peak file (BED format) or GRanges object, or a list of peak files/GRanges objects for comparing multiple datasets |
weightCol |
character, name of a metadata column in the GRanges object to use as weights for coverage calculation. If NULL, all peaks have equal weight. Default is NULL |
xlab |
character, label for x-axis. Default is "Chromosome Size (bp)" |
ylab |
character, label for y-axis. Default is "" (empty) |
title |
character, plot title. Default is "ChIP Peaks over Chromosomes" |
chrs |
character vector, selected chromosomes to plot. If NULL, all chromosomes in the data are plotted. Default is NULL |
xlim |
numeric vector of length 2, genomic range to plot (start, end). If NULL, the entire chromosome is shown. Note: this applies to all chromosomes if specified. Default is NULL |
lower |
numeric, lower cutoff for coverage signal. Regions with coverage below this value are not displayed. Default is 1 |
fill_color |
character vector or single value. For single peak: a color name or hex code. For multiple peaks (list): either a vector of colors (one per peak set) or a palette name (e.g., "Set1", "Dark2") from RColorBrewer. The order of colors matches the order of peak sets. Default is "black" |
This function visualizes the coverage of ChIP-seq peaks across chromosomes, showing the density and distribution of peaks along the genome.
The function performs the following steps:
Loads peaks from file or uses provided GRanges object
Calculates coverage using coverage() function, optionally
weighted by a metadata column
Filters coverage by the lower threshold to remove low signals
Aggregates coverage into contiguous regions
Creates a ggplot2 visualization with:
One facet per chromosome (if multiple chromosomes)
Rectangular bars showing coverage regions
Color coding for multiple peak sets (if input is a list)
For multiple peak sets (list input), the function automatically assigns colors and creates a grouped plot showing all sets together.
A ggplot2 object that can be further customized or printed. The plot shows peak coverage as rectangular bars, with one panel per chromosome when multiple chromosomes are present
G Yu
The csAnno class is the main output object from annotatePeak().
It stores annotated peaks as a GRanges object along with metadata about the
annotation process and summary statistics. This object can be used for
visualization, further analysis, and conversion to other formats.
This class represents the output of ChIPseeker peak annotation. It contains annotated peaks along with their genomic annotations, nearest gene information, and annotation statistics.
The class contains the following slots:
anno: GRanges object containing all annotated peaks with
metadata columns (annotation, geneId, distanceToTSS, etc.)
tssRegion: numeric vector of length 2 specifying the TSS
region used for promoter annotation (e.g., c(-3000, 3000))
level: character, annotation level - either "transcript" or
"gene"
hasGenomicAnnotation: logical, whether genomic feature
annotations (Promoter, Exon, UTR, etc.) were assigned
detailGenomicAnnotation: data.frame with logical columns
indicating which genomic features each peak overlaps
annoStat: data.frame containing annotation statistics showing
the percentage of peaks in each genomic feature category
peakNum: numeric, total number of peaks that were annotated
annoGRanges object containing annotated peaks with all metadata
tssRegionnumeric vector of length 2, TSS region for promoter annotation
levelcharacter, annotation level ("transcript" or "gene")
hasGenomicAnnotationlogical, whether genomic annotations were assigned
detailGenomicAnnotationdata.frame, detailed genomic annotation matrix
annoStatdata.frame, annotation statistics summary
peakNumnumeric, total number of annotated peaks
Guangchuang Yu https://guangchuangyu.github.io
download all BED files of a particular genome version
downloadGEObedFiles(genome, destDir = getwd())downloadGEObedFiles(genome, destDir = getwd())
genome |
genome version |
destDir |
destination folder |
G Yu
download BED supplementary files of a list of GSM accession numbers
downloadGSMbedFiles(GSM, destDir = getwd())downloadGSMbedFiles(GSM, destDir = getwd())
GSM |
GSM accession numbers |
destDir |
destination folder |
G Yu
dropAnno
dropAnno(csAnno, distanceToTSS_cutoff = 10000)dropAnno(csAnno, distanceToTSS_cutoff = 10000)
csAnno |
output of annotatePeak |
distanceToTSS_cutoff |
distance to TSS cutoff |
drop annotation exceeding distanceToTSS_cutoff
csAnno object
Guangchuang Yu
The function compares the overlap of genes associated with query and target ChIP-seq peaks. It uses a hypergeometric test to determine if the number of overlapping genes is significantly higher than expected by chance, suggesting biological similarity between the experiments.
enrichAnnoOverlap( queryPeak, targetPeak, TxDb = NULL, pAdjustMethod = "BH", chainFile = NULL, distanceToTSS_cutoff = NULL )enrichAnnoOverlap( queryPeak, targetPeak, TxDb = NULL, pAdjustMethod = "BH", chainFile = NULL, distanceToTSS_cutoff = NULL )
queryPeak |
character, path to query peak file (BED format), or GRanges object containing query peaks |
targetPeak |
character vector of target peak file paths, a folder containing bed files, or a list of GRanges objects. Multiple target peaks can be provided for comparison |
TxDb |
TxDb or EnsDb annotation object (already loaded in R). If NULL,
uses |
pAdjustMethod |
character, method for p-value adjustment. Default is
"BH" (Benjamini-Hochberg). See |
chainFile |
character, path to chain file for liftOver conversion if target peaks are in a different genome assembly. Default is NULL |
distanceToTSS_cutoff |
numeric, distance cutoff in base pairs. Peaks with absolute distance to TSS greater than this value will be excluded from the analysis. If NULL, all peaks are included. Default is NULL |
This function tests whether two ChIP-seq experiments share significantly more genes than expected by chance, based on the genes nearest to their peaks.
The function performs the following steps:
Annotates both query and target peaks to find their nearest genes
Optionally filters peaks by distance to TSS using
distanceToTSS_cutoff
Counts the number of overlapping genes between query and target
Performs a hypergeometric test to calculate p-values
Adjusts p-values for multiple testing
The hypergeometric test parameters:
White balls (m): number of unique genes in query peaks
Black balls (n): total genes minus query genes
Drawn (k): number of unique genes in target peaks
Overlap (q): number of overlapping genes
A data.frame with one row per target peak comparison, containing:
qSample: name of the query sample
tSample: name of the target sample(s)
qLen: number of unique genes in query peaks
tLen: number of unique genes in target peaks
N_OL: number of overlapping genes. Note that this counts
genes, not peaks, so it can be larger than the number of input
peaks: one peak is annotated to its nearest gene, but the same gene is
reported once per peak and a peak region may overlap several target
genes (see issue #84)
pvalue: p-value from hypergeometric test
p.adjust: adjusted p-value
G Yu
The function compares the genomic overlap between query and target ChIP-seq peaks. It uses a permutation test approach: randomly shuffling target peaks across the genome and comparing the observed overlap to the distribution of overlaps from shuffled data. This provides a p-value indicating whether the observed overlap is significantly higher than expected by chance.
enrichPeakOverlap( queryPeak, targetPeak, TxDb = NULL, pAdjustMethod = "BH", nShuffle = 1000, chainFile = NULL, pool = TRUE, mc.cores = detectCores() - 1, verbose = TRUE, symmetric = FALSE )enrichPeakOverlap( queryPeak, targetPeak, TxDb = NULL, pAdjustMethod = "BH", nShuffle = 1000, chainFile = NULL, pool = TRUE, mc.cores = detectCores() - 1, verbose = TRUE, symmetric = FALSE )
queryPeak |
character, path to query peak file (BED format), or GRanges object containing query peaks |
targetPeak |
character vector of target peak file paths, a folder containing bed files, or a list of GRanges objects. Multiple target peaks can be provided |
TxDb |
TxDb or EnsDb annotation object (already loaded in R). Required
for shuffling peaks (to get chromosome lengths). If NULL, uses
|
pAdjustMethod |
character, method for p-value adjustment. Default is
"BH" (Benjamini-Hochberg). See |
nShuffle |
integer, number of permutations for the statistical test. More shuffles provide more accurate p-values but take longer. Default is 1000. Set to 0 to skip permutation testing (p-value will be NA) |
chainFile |
character, path to chain file for liftOver conversion if target peaks are in a different genome assembly. Default is NULL |
pool |
logical, whether to pool all target peaks together for a single test. If TRUE, tests overlap with the combined set of all target peaks. If FALSE, tests overlap with each target peak set separately. Default is TRUE |
mc.cores |
integer, number of CPU cores to use for parallel processing.
Default is |
verbose |
logical, whether to print progress messages. Default is TRUE |
symmetric |
logical, whether the p-value should be direction free.
Default is FALSE, which reports the one-sided test described above. If
TRUE, the mirrored direction (query and target exchanged) is computed as
well and the two are combined as |
This function tests whether two ChIP-seq experiments have significantly more overlapping peaks than expected by chance, using permutation testing with shuffled peak positions.
The function performs the following steps:
Loads query and target peaks (supports BED files or GRanges objects)
Optionally converts target peaks to query genome using liftOver
(if chainFile is provided)
If pool=TRUE, pools all target peaks and tests overlap with
the pooled set
If pool=FALSE, tests overlap with each target peak set separately
For permutation testing:
Calculates the observed overlap ratio (overlapping peaks / total target peaks)
Randomly shuffles target peaks nShuffle times across the
genome (preserving chromosome and peak width)
Calculates overlap ratio for each shuffled set
Computes p-value as (number of shuffled ratios >= observed ratio + 1) / (nShuffle + 1)
Adjusts p-values for multiple testing
Direction of the test. The observed quantity is the fraction of
target peaks covered by the query peaks,
N_OL / length(targetPeak), and the null distribution is generated by
shuffling the target peaks. The test therefore answers "are the query
peaks enriched within the target peaks?". N_OL itself is symmetric
(it is the same number in both directions), but the p-value is not:
exchanging queryPeak and targetPeak asks the mirrored question
and normalises by the other peak set, so the p-values can differ
substantially when the two peak sets differ in size. Even for equally sized
sets the two null distributions are sampled independently, which leaves
small Monte-Carlo differences (see issue #84). Compare N_OL directly
if a direction-free measure is needed, increase nShuffle to reduce
the Monte-Carlo part, or use symmetric=TRUE for a direction-free
p-value (the mirrored direction is then computed as well and combined as
min(1, 2*min(p, p_rev)), which doubles the number of permutations
and raises the smallest reportable p-value to 2/(nShuffle+1)).
A data.frame with one row per target peak comparison, containing:
qSample: name of the query sample
tSample: name of the target sample(s)
qLen: number of peaks in query
tLen: number of peaks in target (or pooled target if pool=TRUE)
N_OL: number of overlapping peaks
pvalue: p-value from permutation test (NA if nShuffle=0)
p.adjust: adjusted p-value
G Yu
The function filters GRanges objects by converting them to a data.frame, applying the dplyr filter operation, and converting back to GRanges. This allows filtering based on any metadata column or standard GRanges columns (seqnames, start, end, width, strand).
## S3 method for class 'GRanges' filter(.data, ..., .by = NULL, .preserve = FALSE)## S3 method for class 'GRanges' filter(.data, ..., .by = NULL, .preserve = FALSE)
.data |
GRanges object to filter |
... |
logical expressions indicating which ranges to keep. Can use any column names from the GRanges metadata or standard GRanges columns (seqnames, start, end, width, strand). Multiple conditions are combined with AND logic |
.by |
optional grouping variable (for dplyr compatibility). Currently not used but included for API consistency |
.preserve |
logical, whether to preserve grouping structure (for dplyr compatibility). Currently not used but included for API consistency. Default is FALSE |
This function extends dplyr::filter() to work with GRanges objects,
allowing users to filter genomic ranges using familiar dplyr syntax while
preserving the GRanges structure and all metadata columns.
The function performs the following steps:
Converts GRanges to data.frame using as.data.frame()
Applies dplyr::filter() with the provided conditions
Removes unused factor levels using droplevels()
Converts back to GRanges using makeGRangesFromDataFrame()
with keep.extra.columns=TRUE
All metadata columns are preserved in the output. The function supports
all standard dplyr filter operations including logical operators, comparisons,
and functions like is.na(), between(), etc.
GRanges object containing only the filtered ranges that satisfy the conditions. All metadata columns are preserved, and unused factor levels are dropped
## Not run: ## Filter peaks by annotation filtered_peaks <- peak.gr %>% filter(annotation == "Promoter") ## Filter by distance to TSS near_peaks <- peak.gr %>% filter(abs(distanceToTSS) < 5000) ## Multiple conditions (AND logic) specific_peaks <- peak.gr %>% filter(annotation == "Promoter", abs(distanceToTSS) < 3000) ## Filter by chromosome chr1_peaks <- peak.gr %>% filter(seqnames == "chr1") ## Complex conditions complex_filter <- peak.gr %>% filter(annotation %in% c("Promoter", "5' UTR"), !is.na(geneId), width > 200) ## End(Not run)## Not run: ## Filter peaks by annotation filtered_peaks <- peak.gr %>% filter(annotation == "Promoter") ## Filter by distance to TSS near_peaks <- peak.gr %>% filter(abs(distanceToTSS) < 5000) ## Multiple conditions (AND logic) specific_peaks <- peak.gr %>% filter(annotation == "Promoter", abs(distanceToTSS) < 3000) ## Filter by chromosome chr1_peaks <- peak.gr %>% filter(seqnames == "chr1") ## Complex conditions complex_filter <- peak.gr %>% filter(annotation %in% c("Promoter", "5' UTR"), !is.na(geneId), width > 200) ## End(Not run)
The function returns the annoStat slot, which contains a summary of
how peaks are distributed across different genomic feature categories
(Promoter, Exon, Intron, UTR, Intergenic, etc.) with percentages.
getAnnoStat(x)getAnnoStat(x)
x |
|
This function extracts the annotation statistics data frame from a
csAnno object.
A data.frame with columns:
Feature: genomic feature category (Promoter, 5' UTR, 3' UTR,
Exon, Intron, Downstream, Intergenic, etc.)
Frequency: percentage of peaks in each category
Only available if hasGenomicAnnotation=TRUE
Guangchuang Yu https://guangchuangyu.github.io
plotAnnoBar for visualizing these statistics
## Not run: stats <- getAnnoStat(peakAnno) ## View annotation distribution print(stats) ## End(Not run)## Not run: stats <- getAnnoStat(peakAnno) ## View annotation distribution print(stats) ## End(Not run)
The function extracts genomic regions based on feature type and region type. It supports three region types:
start_site: Region around the transcription start site (TSS).
For a transcript at chr1:1000-1400, with upstream=100 and downstream=100,
this extracts chr1:900-1100 (TSS +/- 100bp)
end_site: Region around the transcription termination site (TTS).
For a transcript at chr1:1000-1400, with upstream=100 and downstream=100,
this extracts chr1:1300-1500 (TTS +/- 100bp)
body: The full feature body. For a transcript at chr1:1000-1400,
this extracts chr1:1000-1400 (the entire transcript)
getBioRegion( TxDb = NULL, upstream = 1000, downstream = 1000, by = "gene", type = "start_site" )getBioRegion( TxDb = NULL, upstream = 1000, downstream = 1000, by = "gene", type = "start_site" )
TxDb |
TxDb or EnsDb annotation object. If NULL, will attempt to determine from the data |
upstream |
numeric, distance in base pairs to extend upstream from start
site or end site. For |
downstream |
numeric, distance in base pairs to extend downstream from
start site or end site. For |
by |
character, one of 'gene', 'transcript', 'exon', 'intron', '3UTR', '5UTR', 'UTR'. Determines which feature type to extract. Default is "gene" |
type |
character, one of "start_site", "end_site", "body". Determines which part of the feature to extract. Default is "start_site" |
This function extracts biological regions (promoters, gene bodies, UTRs, etc.) from a TxDb or EnsDb annotation object. It provides a unified interface for extracting different types of genomic regions.
The function supports multiple feature types:
gene: Gene-level regions
transcript: Transcript-level regions
exon: Exon regions
intron: Intron regions
3UTR, 5UTR, UTR: UTR regions
For start_site and end_site types, the function creates regions
extending upstream and downstream from the site. For body type, it
returns the full feature body. The function handles strand information
correctly (upstream/downstream are relative to the feature's strand).
GRanges object containing the extracted regions with attributes:
type: The region type ("start_site", "end_site", or "body")
by: The feature type used
label: Generated label for the regions
upstream: Upstream distance (for start_site/end_site)
downstream: Downstream distance (for start_site/end_site)
Guangchuang Yu, Ming L
getPromoters for a convenience function to get promoters,
makeBioRegionFromGranges for creating regions from custom GRanges
The function queries an annotation database to retrieve gene information such as gene symbols, full gene names, Ensembl IDs, and other identifiers. It handles both Entrez Gene IDs and Ensembl Gene IDs, and returns a data frame with the requested annotation columns.
getGeneAnno(annoDb, geneID, type, columns)getGeneAnno(annoDb, geneID, type, columns)
annoDb |
character, name of the annotation database package (e.g., "org.Hs.eg.db" for human). The package must be installed and loaded |
geneID |
character vector of gene IDs to query. Can be Entrez Gene IDs
or Ensembl Gene IDs depending on the |
type |
character, gene ID type. Must be one of "Entrez Gene ID" or "Ensembl gene ID" / "Ensembl Gene ID" |
columns |
character vector, names of columns to retrieve from the annotation database. Common values include "SYMBOL", "GENENAME", "ENSEMBL", "ENTREZID", "GO", "PATH", etc. See the annotation package documentation for available columns |
This function retrieves gene annotations (symbol, gene name, etc.) from annotation databases (e.g., org.Hs.eg.db) based on gene IDs.
The function performs the following steps:
Validates and converts the gene ID type to the appropriate keytype for the annotation database (ENTREZID or ENSEMBL)
Removes version numbers from Ensembl IDs (e.g., "ENSG00000123456.1" becomes "ENSG00000123456")
Queries the annotation database using AnnotationDbi::select()
Handles duplicate gene IDs by keeping only the first occurrence
Returns a data frame with rows matching the input gene IDs
A data.frame with:
Rows corresponding to the input gene IDs (in the same order)
Columns as specified in the columns parameter, plus the
keytype column (ENTREZID or ENSEMBL)
NA values for gene IDs that could not be found in the database
Returns NA if the ID type is not supported or if the database query fails
G Yu
get genome version statistics collecting from GEO ChIPseq data
getGEOgenomeVersion()getGEOgenomeVersion()
data.frame
G Yu
get subset of GEO information by genome version keyword
getGEOInfo(genome, simplify = TRUE)getGEOInfo(genome, simplify = TRUE)
genome |
genome version |
simplify |
simplify result or not |
data.frame
G Yu
accessing species statistics collecting from GEO database
getGEOspecies()getGEOspecies()
data.frame
G Yu
The function finds the closest feature to each peak by considering both upstream
and downstream directions. It calculates distances from both the peak start and
peak end to the feature's TSS, then selects the feature with the minimum absolute
distance. The function handles overlaps between peaks and features, with different
behaviors depending on the overlap parameter.
getNearestFeatureIndicesAndDistances( peaks, features, sameStrand = FALSE, ignoreOverlap = FALSE, ignoreUpstream = FALSE, ignoreDownstream = FALSE, overlap = "TSS" )getNearestFeatureIndicesAndDistances( peaks, features, sameStrand = FALSE, ignoreOverlap = FALSE, ignoreUpstream = FALSE, ignoreDownstream = FALSE, overlap = "TSS" )
peaks |
GRanges object containing genomic ranges of peaks |
features |
GRanges object containing genomic features (genes or
transcripts) to search for nearest features. Typically obtained from
|
sameStrand |
logical, whether to only consider features on the same strand as the peak, both when finding the nearest feature and when detecting overlaps with it. If FALSE, searches both strands. Peaks with ambiguous strand ('*') are compatible with features on any strand. Default is FALSE |
ignoreOverlap |
logical, whether to ignore overlaps between peaks and features when finding the nearest feature. If FALSE, overlapping features will be prioritized and assigned distance=0 (for TSS overlaps) or calculated distance (for full feature overlaps). Default is FALSE |
ignoreUpstream |
logical, if TRUE, only considers features downstream (3' end) of the peak. This restricts annotation to genes that come after the peak. Default is FALSE |
ignoreDownstream |
logical, if TRUE, only considers features upstream (5' end) of the peak. This restricts annotation to genes that come before the peak. Default is FALSE |
overlap |
character, one of "TSS" or "all". Determines how overlaps are detected and handled:
Default is "TSS" |
This function identifies the nearest gene/transcript feature to each peak and calculates the distance from the peak to the feature's transcription start site (TSS).
The function performs the following steps:
Resizes features to width=1 (TSS points) for efficient distance calculation
Finds nearest upstream features using follow() and nearest
downstream features using precede()
Calculates distances from both peak start and peak end to each feature's TSS
Selects the feature with the minimum absolute distance (or enforces
direction based on ignoreUpstream/ignoreDownstream)
If overlaps are allowed (ignoreOverlap=FALSE), identifies
overlapping features and assigns them with distance=0 (for overlap="TSS")
or calculates distance from the closer peak end (for overlap="all")
Returns indices, distances, and filtered peaks (excluding peaks with no nearest feature)
Distance calculation is strand-aware: positive values indicate downstream, negative values indicate upstream. Overlapping peaks get distance=0 if overlap is "TSS".
A list with three components:
index: Integer vector of feature indices (1-based) for the
nearest feature to each peak. Length equals the number of peaks with
valid nearest features
distance: Numeric vector of distances from each peak to the
TSS of its nearest feature. Positive values indicate downstream, negative
values indicate upstream, and 0 indicates overlap. Length equals the
number of peaks with valid nearest features
peak: GRanges object containing only the peaks that have
valid nearest features (peaks with no nearest feature in either direction
are excluded)
G Yu
The function extracts promoter regions defined as regions around transcription
start sites (TSS). For each gene or transcript, it creates a region extending
upstream and downstream from the TSS. The function calls getBioRegion()
with type="start_site".
getPromoters(TxDb = NULL, upstream = 1000, downstream = 1000, by = "gene")getPromoters(TxDb = NULL, upstream = 1000, downstream = 1000, by = "gene")
TxDb |
TxDb or EnsDb annotation object. If NULL, will attempt to determine from the data |
upstream |
numeric, distance in base pairs to extend upstream from TSS. Default is 1000 |
downstream |
numeric, distance in base pairs to extend downstream from TSS. Default is 1000 |
by |
character, one of "gene" or "transcript". Determines whether to extract promoters at gene level or transcript level. Default is "gene" |
This function extracts promoter regions (TSS regions) from a TxDb or EnsDb
annotation object. It is a convenience wrapper around getBioRegion()
for extracting promoter regions.
GRanges object containing promoter regions with attributes:
type: "start_site"
by: the value of the by parameter
label: generated label for the regions
upstream: upstream distance
downstream: downstream distance
getBioRegion for more flexible region extraction
The function scans the package's extdata directory for sample peak files and returns their paths. The files are named based on the protein/condition they represent (extracted from the filename).
getSampleFiles()getSampleFiles()
This function returns a list of sample ChIP-seq peak files included in the package for demonstration and testing purposes.
A named list of file paths. Names are extracted from filenames (typically protein/condition names), and values are full file paths to the sample BED files
G Yu
The function computes peak coverage across a set of genomic regions (windows). It supports two methods:
Direct method (when nbin=NULL): For regions of equal
size (e.g., promoters), calculates coverage at each base pair position
Binning method (when nbin is specified): For regions
of variable size (e.g., gene bodies), divides each region into a fixed
number of bins and calculates average coverage per bin
getTagMatrix( peak, upstream, downstream, windows, type, by, TxDb = NULL, weightCol = NULL, nbin = NULL, verbose = TRUE, ignore_strand = FALSE )getTagMatrix( peak, upstream, downstream, windows, type, by, TxDb = NULL, weightCol = NULL, nbin = NULL, verbose = TRUE, ignore_strand = FALSE )
peak |
peak file (BED format) or GRanges object containing ChIP-seq peaks |
upstream |
numeric or |
downstream |
numeric or |
windows |
GRanges object containing regions of interest. Should be created
by |
type |
character, one of "start_site", "end_site", "body". Required if
|
by |
character, one of 'gene', 'transcript', 'exon', 'intron', '3UTR',
'5UTR', or user-specified label. Required if |
TxDb |
TxDb/EnsDb object or GRanges object. If TxDb, used to create windows.
If GRanges, treated as custom regions and passed to |
weightCol |
character, name of a metadata column in the peak GRanges to use as weights for coverage calculation. If NULL, all peaks have equal weight. Default is NULL |
nbin |
integer, number of bins for binning method. Required for
|
verbose |
logical, whether to print progress messages. Default is TRUE |
ignore_strand |
logical, whether to ignore strand information when calculating coverage. If FALSE, negative strand regions are reverse-complemented. Default is FALSE |
This function calculates a tag matrix representing peak coverage across genomic
regions (e.g., promoters, gene bodies). The matrix can be used for visualization
with functions like plotPeakProf() or plotAvgProf().
The function can work in two modes:
With pre-made windows: Provide a windows GRanges object
created by getPromoters(), getBioRegion(), or
makeBioRegionFromGranges()
Without windows: Provide TxDb and region parameters
(type, by, upstream, downstream), and the
function will create windows automatically
For upstream and downstream parameters:
If windows is provided: For type='body', these extend
the flanks; for type='start_site'/'end_site', they are ignored
(taken from window attributes)
If windows is missing: These define the region size for
type='start_site'/'end_site', or extend flanks for type='body'
The weightCol parameter allows weighting peaks by a metadata column
(e.g., peak score or signal value), useful for signal-weighted coverage.
A matrix (tagMatrix) with:
Rows: One per region (window)
Columns: One per position/bin
Values: Peak coverage/signal at each position
The matrix has attributes:
upstream: Upstream distance
downstream: Downstream distance
type: Region type
label: Region label
is.binning: Whether binning method was used
getPromoters, getBioRegion,
makeBioRegionFromGranges for creating windows,
plotPeakProf, plotAvgProf for visualization
The function divides each region into a fixed number of bins and calculates average coverage per bin. This allows handling regions of variable size (e.g., gene bodies of different lengths) by normalizing them to the same number of bins. The approach is similar to deeptools computeMatrix (https://deeptools.readthedocs.io/en/develop/content/tools/computeMatrix.html).
getTagMatrix.binning.internal( peak, weightCol = NULL, windows, nbin = 800, upstream = NULL, downstream = NULL, ignore_strand = FALSE )getTagMatrix.binning.internal( peak, weightCol = NULL, windows, nbin = 800, upstream = NULL, downstream = NULL, ignore_strand = FALSE )
peak |
peak file (BED format) or GRanges object containing ChIP-seq peaks |
weightCol |
character, name of a metadata column to use as weights. If NULL, all peaks have equal weight. Default is NULL |
windows |
GRanges object containing regions. Regions can have variable sizes (e.g., gene bodies of different lengths) |
nbin |
integer, number of bins to divide each region into. Should not exceed the minimum region length. Default is 800 |
upstream |
numeric, |
downstream |
numeric, |
ignore_strand |
logical, whether to ignore strand information. If FALSE, negative strand regions are reverse-complemented. Default is FALSE |
This is an internal function that calculates peak coverage using a binning
approach, inspired by deeptools computeMatrix. It is called by getTagMatrix()
when nbin is specified.
The function performs the following steps:
Loads peaks and calculates coverage (optionally weighted)
Filters windows to those within chromosome boundaries
Optionally extends windows by upstream and downstream
(can be relative values using rel())
For each window, divides it into nbin equal-sized bins
Calculates average coverage per bin
Creates a matrix with one row per window and one column per bin
Reverse-complements negative strand regions (if ignore_strand=FALSE)
Filters out windows shorter than the minimum required length
The binning method is essential for visualizing coverage across variable-length regions (e.g., gene bodies), as it normalizes all regions to the same number of data points.
A matrix with:
Rows: One per window (regions meeting minimum length requirement)
Columns: One per bin (nbin columns)
Values: Average coverage/signal per bin
Pre-calculated datasets included in the ChIPseeker package:
ucsc_release: UCSC genome version information
gsminfo: GEO Sample (GSM) information for ChIP-seq datasets
tagMatrixList: Pre-calculated tag matrices for example datasets
The function extracts regions from a custom GRanges object, similar to
getBioRegion() but working with user-defined features instead of TxDb
annotations. This is useful for features like enhancers, insulators, or
other regulatory elements that are not part of standard gene annotations.
makeBioRegionFromGranges(gr, by, type, upstream = 1000, downstream = 1000)makeBioRegionFromGranges(gr, by, type, upstream = 1000, downstream = 1000)
gr |
GRanges object containing regions of interest (e.g., enhancers, insulators, custom regulatory elements) |
by |
character, user-specified label for the feature type (e.g., "gene", "insulator", "enhancer"). Used for generating region labels. Cannot be omitted |
type |
character, one of "start_site", "end_site", "body". Determines which part of each range to extract. Cannot be omitted |
upstream |
numeric or NULL, distance in base pairs to extend upstream
from start site or end site. Can be NULL if |
downstream |
numeric or NULL, distance in base pairs to extend downstream
from start site or end site. Can be NULL if |
This function creates biological regions from a user-provided GRanges object, allowing extraction of regions around start sites, end sites, or full bodies for custom genomic features not available in TxDb objects (e.g., enhancers, insulators).
The function supports three region types:
start_site: Region around the start of each range. For an
enhancer at chr1:1000-1400 with upstream=100 and downstream=100,
extracts chr1:900-1100 (start +/- 100bp, strand-aware)
end_site: Region around the end of each range. For an enhancer
at chr1:1000-1400 with upstream=100 and downstream=100, extracts
chr1:1300-1500 (end +/- 100bp, strand-aware)
body: The full range body. For an enhancer at chr1:1000-1400,
extracts chr1:1000-1400. For this type, upstream and
downstream can be NULL
The function handles strand information correctly: for negative strand features, "upstream" and "downstream" are reversed relative to the genomic coordinates.
GRanges object containing the extracted regions with attributes:
type: The region type
by: The feature type label
label: Generated label for the regions
upstream: Upstream distance (for start_site/end_site)
downstream: Downstream distance (for start_site/end_site)
getBioRegion for extracting regions from TxDb objects
The function mutates GRanges objects by converting them to a data.frame, applying the dplyr mutate operation, and converting back to GRanges. This allows creating new columns or modifying existing metadata columns based on expressions involving other columns.
## S3 method for class 'GRanges' mutate( .data, ..., .by = NULL, .keep = c("all", "used", "unused", "none"), .before = NULL, .after = NULL )## S3 method for class 'GRanges' mutate( .data, ..., .by = NULL, .keep = c("all", "used", "unused", "none"), .before = NULL, .after = NULL )
.data |
GRanges object to mutate |
... |
name-value pairs of expressions. Use |
.by |
optional grouping variable (for dplyr compatibility). Currently not used but included for API consistency |
.keep |
character, which columns to keep. Options: "all" (keep all columns), "used" (keep only columns used in expressions), "unused" (keep only columns not used in expressions), "none" (keep only new columns). Default is "all" |
.before, .after
|
column position specifiers. Place new columns before or after the specified column. Cannot use both. If NULL, new columns are appended at the end. Default is NULL for both |
This function extends dplyr::mutate() to work with GRanges objects,
allowing users to add new metadata columns or modify existing ones using
familiar dplyr syntax while preserving the GRanges structure.
The function performs the following steps:
Converts GRanges to data.frame using as.data.frame()
Validates that .before and .after are not both specified
Applies dplyr::mutate() with the provided expressions,
handling column positioning if .before or .after is specified
Converts back to GRanges using makeGRangesFromDataFrame()
with keep.extra.columns=TRUE
All genomic range information (seqnames, ranges, strand) is preserved. The function supports all standard dplyr mutate operations including arithmetic, logical operations, and functions.
GRanges object with modified or new metadata columns. All genomic
range information is preserved. The order and position of new columns
follows the .before or .after specifications
## Not run: ## Add a new column based on existing data peak.gr <- peak.gr %>% mutate(logScore = log10(score)) ## Modify existing column peak.gr <- peak.gr %>% mutate(distance = abs(distanceToTSS)) ## Create multiple columns peak.gr <- peak.gr %>% mutate( distance_kb = abs(distanceToTSS) / 1000, is_promoter = annotation == "Promoter", category = ifelse(abs(distanceToTSS) < 3000, "near", "far") ) ## Place new column before specific column peak.gr <- peak.gr %>% mutate(new_col = 1, .before = annotation) ## Keep only used columns peak.gr <- peak.gr %>% mutate(result = score * 2, .keep = "used") ## End(Not run)## Not run: ## Add a new column based on existing data peak.gr <- peak.gr %>% mutate(logScore = log10(score)) ## Modify existing column peak.gr <- peak.gr %>% mutate(distance = abs(distanceToTSS)) ## Create multiple columns peak.gr <- peak.gr %>% mutate( distance_kb = abs(distanceToTSS) / 1000, is_promoter = annotation == "Promoter", category = ifelse(abs(distanceToTSS) < 3000, "near", "far") ) ## Place new column before specific column peak.gr <- peak.gr %>% mutate(new_col = 1, .before = annotation) ## Keep only used columns peak.gr <- peak.gr %>% mutate(result = score * 2, .keep = "used") ## End(Not run)
The function computes the number of elements in each possible intersection of the input sets. It handles all combinations of set intersections using an inclusion-exclusion principle approach.
overlap(Sets)overlap(Sets)
Sets |
list of objects (e.g., GRanges objects, character vectors, etc.)
to calculate overlaps for. Each element should support |
This function calculates the overlap matrix for multiple sets, which is useful for creating Venn diagrams and understanding set relationships.
The function:
Generates all possible combinations of set inclusion/exclusion
For each combination, calculates the intersection size
Uses inclusion-exclusion principle to handle overlapping intersections
Returns a data frame with binary indicators for each set and the intersection size
The function is generic and works with any objects that support intersect()
and length() methods, including GRanges objects.
A data.frame with:
One column per set (named after the sets)
Binary values (0 or 1) indicating which sets are included in each intersection
A "Weight" column containing the number of elements in each intersection
Rows represent all possible combinations of set intersections
G Yu
The function generates a two-panel figure:
Top panel: Heatmap showing signal intensity for each feature (row) across genomic positions (columns)
Bottom panel: Average profile line showing the mean signal across all features at each position
This combination allows users to see both individual feature patterns and the overall trend simultaneously.
peak_Profile_Heatmap( peak, weightCol = NULL, TxDb = NULL, upstream = 1000, downstream = 1000, xlab = "", ylab = "", title = NULL, palette = NULL, verbose = TRUE, by = "gene", type = "start_site", nbin = NULL, ignore_strand = FALSE, windows_name = NULL, ncol = NULL, nrow = NULL, facet_label_text_size = 12, conf, facet = "row", free_y = TRUE, height_proportion = 4 )peak_Profile_Heatmap( peak, weightCol = NULL, TxDb = NULL, upstream = 1000, downstream = 1000, xlab = "", ylab = "", title = NULL, palette = NULL, verbose = TRUE, by = "gene", type = "start_site", nbin = NULL, ignore_strand = FALSE, windows_name = NULL, ncol = NULL, nrow = NULL, facet_label_text_size = 12, conf, facet = "row", free_y = TRUE, height_proportion = 4 )
peak |
peak file (BED format) or GRanges object, or a named list of peak files/GRanges objects for comparing multiple datasets |
weightCol |
character, name of metadata column to use as weights. If NULL, all peaks have equal weight. Default is NULL |
TxDb |
TxDb or EnsDb annotation object, or a GRanges object containing custom genomic features |
upstream |
numeric, upstream distance in base pairs. Default is 1000 |
downstream |
numeric, downstream distance in base pairs. Default is 1000 |
xlab |
character, x-axis label. Default is "" (empty) |
ylab |
character, y-axis label. Default is "" (empty) |
title |
character, plot title. If NULL, no title is shown. Default is NULL |
palette |
character, color palette name from RColorBrewer for the heatmap.
See |
verbose |
logical, whether to print progress messages. Default is TRUE |
by |
character, feature type. With TxDb: one of "gene", "transcript", "exon", "intron", "3UTR", "5UTR", "UTR". Default is "gene" |
type |
character, one of "start_site", "end_site", or "body". Default is "start_site" |
nbin |
integer, number of bins for binning mode. If NULL, uses absolute positioning. Default is NULL |
ignore_strand |
logical, whether to ignore strand information. Default is FALSE |
windows_name |
character vector, names for windows (for multi-window plots). Default is NULL |
ncol |
integer, number of columns for arranging multiple plots. Default is NULL |
nrow |
integer, number of rows for arranging multiple plots. Default is NULL |
facet_label_text_size |
numeric, size of facet label text. Default is 12 |
conf |
numeric, confidence level for confidence intervals in the profile plot (e.g., 0.95). If NA or missing, no confidence intervals are shown |
facet |
character, one of "none", "row", or "column" for faceting the profile plot. Default is "none" |
free_y |
logical, if TRUE, y-axis scales independently per facet in the profile plot. Default is TRUE |
height_proportion |
numeric, proportion of height allocated to profile plot vs heatmap. Values between 0 and 1, where 0.5 means equal heights. Default is 0.5 |
This function creates a combined visualization showing both a heatmap of individual features and an average profile line plot in a single figure, providing both detailed and summary views of peak distributions.
The function generates tag matrices from peaks and visualizes them as heatmaps. It supports both absolute positioning and binning modes. Features are typically sorted by signal strength, allowing identification of features with strong peak enrichment.
peakHeatmap( peak, weightCol = NULL, TxDb = NULL, upstream = 1000, downstream = 1000, xlab = "", ylab = "", title = NULL, palette = NULL, verbose = TRUE, by = "gene", type = "start_site", nbin = NULL, ignore_strand = FALSE, windows, ncol = NULL, nrow = NULL )peakHeatmap( peak, weightCol = NULL, TxDb = NULL, upstream = 1000, downstream = 1000, xlab = "", ylab = "", title = NULL, palette = NULL, verbose = TRUE, by = "gene", type = "start_site", nbin = NULL, ignore_strand = FALSE, windows, ncol = NULL, nrow = NULL )
peak |
peak file (BED format) or GRanges object, or a named list of peak files/GRanges objects for comparing multiple datasets |
weightCol |
character, name of metadata column to use as weights. If NULL, all peaks have equal weight. Default is NULL |
TxDb |
TxDb or EnsDb annotation object, or a GRanges object containing custom genomic features |
upstream |
numeric, upstream distance in base pairs. Default is 1000 |
downstream |
numeric, downstream distance in base pairs. Default is 1000 |
xlab |
character, x-axis label. Default is "" (empty) |
ylab |
character, y-axis label. Default is "" (empty) |
title |
character, plot title. If NULL, no title is shown. Default is NULL |
palette |
character, color palette name from RColorBrewer. If NULL, uses
default. See |
verbose |
logical, whether to print progress messages. Default is TRUE |
by |
character, feature type. With TxDb: one of "gene", "transcript", "exon", "intron", "3UTR", "5UTR", "UTR". Default is "gene" |
type |
character, one of "start_site", "end_site", or "body". Default is "start_site" |
nbin |
integer, number of bins for binning mode. If NULL, uses absolute positioning. Default is NULL |
ignore_strand |
logical, whether to ignore strand information. Default is FALSE |
windows |
GRanges object, custom genomic regions to use instead of generating from TxDb. If missing, regions are generated from TxDb. Default is missing |
ncol |
integer, number of columns for arranging multiple heatmaps. Default is NULL |
nrow |
integer, number of rows for arranging multiple heatmaps. Default is NULL |
This function creates a heatmap showing the distribution of ChIP-seq peaks around genomic features (e.g., TSS, gene body). Each row represents a feature and each column represents a genomic position.
The function:
Generates tag matrices from peaks using getTagMatrix()
Optionally uses custom windows (if provided) or generates them from
TxDb based on by and type
Creates heatmap visualization with color-coded signal intensities
Supports single or multiple peak sets (list input)
A ggplot2 heatmap object showing peak signals across features and positions. For multiple peak sets, returns a grid of heatmaps
G Yu
The function extends peakHeatmap() to support multiple window sets.
It generates tag matrices for each window set and creates a faceted heatmap
visualization, with each facet showing peaks aligned to a different set of
regions. This is useful for comparing peak patterns across different feature
types (e.g., promoters vs enhancers) or conditions.
peakHeatmap_multiple_Sets( peak, weightCol = NULL, TxDb = NULL, upstream = 1000, downstream = 1000, xlab = "", ylab = "", title = NULL, palette = NULL, verbose = TRUE, by = "gene", type = "start_site", nbin = NULL, ignore_strand = FALSE, windows_name = NULL, ncol = NULL, nrow = NULL, facet_label_text_size = 12 )peakHeatmap_multiple_Sets( peak, weightCol = NULL, TxDb = NULL, upstream = 1000, downstream = 1000, xlab = "", ylab = "", title = NULL, palette = NULL, verbose = TRUE, by = "gene", type = "start_site", nbin = NULL, ignore_strand = FALSE, windows_name = NULL, ncol = NULL, nrow = NULL, facet_label_text_size = 12 )
peak |
peak file (BED format) or GRanges object, or a named list of peak files/GRanges objects for comparing multiple datasets |
weightCol |
character, name of metadata column to use as weights. If NULL, all peaks have equal weight. Default is NULL |
TxDb |
TxDb or EnsDb annotation object, or a named list of GRanges objects containing custom genomic features. If a list, names are used as window names |
upstream |
numeric, upstream distance in base pairs. Must be the same for all windows. Default is 1000 |
downstream |
numeric, downstream distance in base pairs. Must be the same for all windows. Default is 1000 |
xlab |
character, x-axis label. Default is "" (empty) |
ylab |
character, y-axis label. Default is "" (empty) |
title |
character, plot title. If NULL, no title is shown. Default is NULL |
palette |
character, color palette name from RColorBrewer. If NULL, uses default. Default is NULL |
verbose |
logical, whether to print progress messages. Default is TRUE |
by |
character vector, feature types for each window. With TxDb: one of "gene", "transcript", "exon", "intron", "3UTR", "5UTR", "UTR". Length must match number of windows. Default is "gene" |
type |
character, one of "start_site", "end_site", or "body". Must be the same for all windows. Default is "start_site" |
nbin |
integer, number of bins for binning mode. If NULL, uses absolute positioning. Default is NULL |
ignore_strand |
logical, whether to ignore strand information. Default is FALSE |
windows_name |
character vector, names for each window (displayed as facet labels). If NULL and TxDb is a named list, uses names from TxDb. Default is NULL |
ncol |
integer, number of columns for arranging heatmaps. Default is NULL (auto) |
nrow |
integer, number of rows for arranging heatmaps. Default is NULL (auto) |
facet_label_text_size |
numeric, size of facet label text. Default is 12 |
This function creates heatmaps showing peak distributions across multiple sets of genomic regions (windows), allowing comparison of peak patterns across different feature types or conditions.
The function:
Generates tag matrices for each window set (specified via by
or custom TxDb GRanges)
Creates heatmaps for each window set
Arranges them in a grid with faceting
Supports both absolute positioning and binning modes
All windows must have the same type (start_site, end_site, or body)
and the same upstream and downstream parameters.
figure
The function visualizes the percentage of peaks falling into each genomic
annotation category. It creates a horizontal bar chart where each bar
represents a category, and the bar length represents the percentage of peaks
in that category. The function supports both single csAnno objects
and lists of csAnno objects for comparing multiple datasets.
plotAnnoBar( x, xlab = "", ylab = "Percentage(%)", title = "Feature Distribution", ... )plotAnnoBar( x, xlab = "", ylab = "Percentage(%)", title = "Feature Distribution", ... )
x |
|
xlab |
character, label for x-axis. Default is "" (empty) |
ylab |
character, label for y-axis. Default is "Percentage(%)" |
title |
character, plot title. Default is "Feature Distribution" |
... |
additional parameters passed to the implementation methods |
This generic function creates a bar plot showing the distribution of peaks across different genomic annotation categories (Promoter, Exon, Intron, etc.).
The function:
Extracts annotation statistics from the csAnno object(s)
Calculates percentages for each annotation category
Creates a horizontal bar chart with categories on the y-axis and percentages on the x-axis
Color-codes each annotation category
Common annotation categories include: Promoter, 5' UTR, 3' UTR, Exon, Intron, Downstream, and Intergenic.
A ggplot2 bar plot object showing the distribution of peaks across
genomic annotation categories. For lists of csAnno objects, the plot
shows side-by-side bars for comparison
plotAnnoPie for pie chart visualization,
annotatePeak for peak annotation
plot feature distribution based on their chromosome region
plotAnnoBar.data.frame( anno.df, xlab = "", ylab = "Percentage(%)", title = "Feature Distribution", categoryColumn )plotAnnoBar.data.frame( anno.df, xlab = "", ylab = "Percentage(%)", title = "Feature Distribution", categoryColumn )
anno.df |
annotation stats |
xlab |
xlab |
ylab |
ylab |
title |
plot title |
categoryColumn |
category column |
plot chromosome region features
bar plot that summarize genomic features of peaks
Guangchuang Yu https://yulab-smu.top
The function visualizes the percentage of peaks falling into each genomic annotation category using a pie chart. Each slice of the pie represents an annotation category, with the slice size proportional to the percentage of peaks in that category. Labels show the category name and percentage.
plotAnnoPie( x, ndigit = 2, cex = 0.9, col = NA, legend.position = "rightside", pie3D = FALSE, radius = 0.8, ... )plotAnnoPie( x, ndigit = 2, cex = 0.9, col = NA, legend.position = "rightside", pie3D = FALSE, radius = 0.8, ... )
x |
|
ndigit |
integer, number of decimal places to round percentages in labels. Default is 2 |
cex |
numeric, character expansion factor for labels. Larger values make labels bigger. Default is 0.9 |
col |
character vector, colors for pie slices. If NA (default), automatic colors are used |
legend.position |
character, position of the legend. Options include "rightside", "leftside", "top", "bottom", or specific coordinates. Default is "rightside" |
pie3D |
logical, whether to create a 3D pie chart. If TRUE, uses
|
radius |
numeric, radius of the pie chart. Values between 0 and 1. Default is 0.8 |
... |
additional parameters passed to the pie chart plotting functions |
This generic function creates a pie chart showing the distribution of peaks across different genomic annotation categories.
The function:
Extracts annotation statistics from the csAnno object
Calculates percentages for each annotation category
Creates a pie chart with color-coded slices
Adds labels showing category names and percentages (rounded to
ndigit decimal places)
Optionally creates a 3D pie chart for enhanced visualization
Common annotation categories include: Promoter, 5' UTR, 3' UTR, Exon, Intron, Downstream, and Intergenic.
A pie chart plot showing the distribution of peaks across genomic annotation categories. The plot includes labels with category names and percentages, and a legend
plotAnnoBar for bar chart visualization,
vennpie for nested pie chart visualization,
annotatePeak for peak annotation
pieplot from peak genomic annotation
plotAnnoPie.csAnno( x, ndigit = 2, cex = 0.8, col = NA, legend.position = "rightside", pie3D = FALSE, radius = 0.8, ... )plotAnnoPie.csAnno( x, ndigit = 2, cex = 0.8, col = NA, legend.position = "rightside", pie3D = FALSE, radius = 0.8, ... )
x |
csAnno object |
ndigit |
number of digit to round |
cex |
label cex |
col |
color |
legend.position |
topright or other. |
pie3D |
plot in 3D or not |
radius |
radius of Pie |
... |
extra parameter |
pie plot of peak genomic feature annotation
Guangchuang Yu https://yulab-smu.top
## Not run: require(TxDb.Hsapiens.UCSC.hg19.knownGene) txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene peakfile <- system.file("extdata", "sample_peaks.txt", package="chipseeker") peakAnno <- annotatePeak(peakfile, TxDb=txdb) plotAnnoPie(peakAnno) ## End(Not run)## Not run: require(TxDb.Hsapiens.UCSC.hg19.knownGene) txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene peakfile <- system.file("extdata", "sample_peaks.txt", package="chipseeker") peakAnno <- annotatePeak(peakfile, TxDb=txdb) plotAnnoPie(peakAnno) ## End(Not run)
The function creates a line plot showing the average signal intensity of peaks across genomic regions. It can plot single or multiple peak sets, with optional confidence intervals (error bars or ribbons) and faceting options for comparing datasets.
plotAvgProf( tagMatrix, xlim, xlab = "Genomic Region (5'->3')", ylab = "Peak Count Frequency", conf, facet = "none", free_y = TRUE, origin_label = "TSS", verbose = TRUE, ... )plotAvgProf( tagMatrix, xlim, xlab = "Genomic Region (5'->3')", ylab = "Peak Count Frequency", conf, facet = "none", free_y = TRUE, origin_label = "TSS", verbose = TRUE, ... )
tagMatrix |
matrix or list of matrices. Each matrix should have features
as rows and genomic positions as columns. Tag matrices are typically obtained
from |
xlim |
numeric vector of length 2, x-axis limits (start, end positions). Should match the number of columns in tagMatrix. Default example: c(-3000, 3000) |
xlab |
character, x-axis label. Default is "Genomic Region (5'->3')" |
ylab |
character, y-axis label. Default is "Peak Count Frequency" |
conf |
numeric, confidence level (e.g., 0.95 for 95 confidence intervals are calculated and displayed as ribbons. If NA or missing, no confidence intervals are shown |
facet |
character, one of "none", "row", or "column". Controls how multiple datasets are displayed: "none" overlays them, "row" creates row facets, "column" creates column facets. Default is "none" |
free_y |
logical, if TRUE and faceting is used, y-axis scales independently for each facet. Default is TRUE |
origin_label |
character, label for the center point (e.g., "TSS", "TES"). A vertical line is drawn at position 0 with this label. Default is "TSS" |
verbose |
logical, whether to print progress messages. Default is TRUE |
... |
additional arguments passed to ggplot2 functions |
Plot average peak profile
This function plots the average profile of peaks around genomic features (e.g., TSS, gene body) as a line plot, optionally with confidence intervals.
The function:
Calculates average signal across all features for each position
Optionally calculates confidence intervals (if conf is provided)
Creates a line plot with optional ribbon for confidence intervals
Supports faceting for multiple datasets (row, column, or none)
Allows independent y-axis scaling per facet
For multiple datasets (list input), the function automatically creates
separate facets or overlays them based on the facet parameter.
A ggplot2 object showing the average peak profile as a line plot, with optional confidence intervals and faceting
G Yu; Y Yan
plot the profile of peaks that align to flank sequences of TSS
plotAvgProf2( peak, weightCol = NULL, TxDb = NULL, upstream = 1000, downstream = 1000, xlab = "Genomic Region (5'->3')", ylab = "Peak Count Frequency", conf, facet = "none", free_y = TRUE, verbose = TRUE, ignore_strand = FALSE, ... )plotAvgProf2( peak, weightCol = NULL, TxDb = NULL, upstream = 1000, downstream = 1000, xlab = "Genomic Region (5'->3')", ylab = "Peak Count Frequency", conf, facet = "none", free_y = TRUE, verbose = TRUE, ignore_strand = FALSE, ... )
peak |
peak file (BED format) or GRanges object, or a list of peak files/GRanges objects for comparing multiple datasets |
weightCol |
character, name of a metadata column in the GRanges object to use as weights for coverage calculation. If NULL, all peaks have equal weight. Default is NULL |
TxDb |
TxDb or EnsDb annotation object. Default is NULL |
upstream |
numeric, upstream distance in base pairs from the start site. Default is 1000 |
downstream |
numeric, downstream distance in base pairs from the start site. Default is 1000 |
xlab |
character, x-axis label. Default is "Genomic Region (5'->3')" |
ylab |
character, y-axis label. Default is "Peak Count Frequency" |
conf |
numeric, confidence level (e.g., 0.95 for 95 confidence intervals are displayed. If NA or missing, no confidence intervals are shown |
facet |
character, one of "none", "row", or "column". Controls how multiple datasets are displayed. Default is "none" |
free_y |
logical, if TRUE and faceting is used, y-axis scales independently for each facet. Default is TRUE |
verbose |
logical, whether to print progress messages. Default is TRUE |
ignore_strand |
logical, whether to ignore strand information when calculating coverage. Default is FALSE |
... |
additional arguments passed to ggplot2 functions |
This function is the old function of plotPeakProf2. It can
only plot the start site region of gene.
ggplot object
G Yu, Ming L
The function visualizes where ChIP-seq peaks are located relative to gene TSSs. It categorizes peaks into distance bins (e.g., 0-1kb, 1-3kb, etc.) and displays the percentage of peaks in each category, separately for upstream (5') and downstream (3') regions. The plot uses a diverging bar chart with TSS at the center (0).
plotDistToTSS( x, distanceColumn = "distanceToTSS", xlab = "", ylab = "Binding sites (%) (5'->3')", title = "Distribution of transcription factor-binding loci relative to TSS", ... )plotDistToTSS( x, distanceColumn = "distanceToTSS", xlab = "", ylab = "Binding sites (%) (5'->3')", title = "Distribution of transcription factor-binding loci relative to TSS", ... )
x |
|
distanceColumn |
character, name of the column containing distances from peaks to nearest gene TSS. Default is "distanceToTSS" |
xlab |
character, label for x-axis. Default is "" (empty) |
ylab |
character, label for y-axis. Default is "Binding sites (%) (5'->3')" |
title |
character, plot title. Default is "Distribution of transcription factor-binding loci relative to TSS" |
... |
additional parameters passed to the implementation methods, such as:
|
This generic function creates a bar plot showing the distribution of peaks relative to transcription start sites (TSS), categorizing peaks by their distance from the nearest gene's TSS.
The function:
Categorizes peaks into distance bins based on distanceBreaks
Separates upstream (negative distance) and downstream (positive distance) peaks
Calculates percentages for each distance category
Creates a diverging bar plot with upstream peaks on the left and downstream peaks on the right, with TSS at the center
A ggplot2 bar plot object showing the distribution of peaks relative to TSS. The plot uses a diverging bar chart format with upstream (5') on the left and downstream (3') on the right, with TSS at the center
annotatePeak for peak annotation,
plotAnnoBar for annotation distribution plots
The function visualizes where ChIP-seq peaks are located relative to gene TSSs. It categorizes peaks into distance bins (e.g., 0-1kb, 1-3kb, etc.) and displays the percentage of peaks in each category, separately for upstream (5') and downstream (3') regions. The plot uses a diverging bar chart with TSS at the center (0).
plotDistToTSS.data.frame( peakDist, distanceColumn = "distanceToTSS", distanceBreaks = c(0, 1000, 3000, 5000, 10000, 1e+05), palette = NULL, xlab = "", ylab = "Binding sites (%) (5'->3')", title = "Distribution of transcription factor-binding loci relative to TSS", categoryColumn = ".id" )plotDistToTSS.data.frame( peakDist, distanceColumn = "distanceToTSS", distanceBreaks = c(0, 1000, 3000, 5000, 10000, 1e+05), palette = NULL, xlab = "", ylab = "Binding sites (%) (5'->3')", title = "Distribution of transcription factor-binding loci relative to TSS", categoryColumn = ".id" )
peakDist |
data.frame containing peak annotation data with a distance
column. Typically obtained from |
distanceColumn |
character, name of the column containing distances from peaks to nearest gene TSS. Default is "distanceToTSS" |
distanceBreaks |
numeric vector, breakpoints for distance categories in base pairs. The function automatically adds 0 and Inf if not present. Default is c(0, 1000, 3000, 5000, 10000, 100000) |
palette |
character, color palette name from RColorBrewer (e.g., "Set1",
"Dark2") or NULL for default colors. Run
|
xlab |
character, label for x-axis. Default is "" (empty) |
ylab |
character, label for y-axis. Default is "Binding sites (%) (5'->3')" |
title |
character, plot title. Default is "Distribution of transcription factor-binding loci relative to TSS" |
categoryColumn |
character or numeric, column name or index for grouping multiple datasets. If 1 or ".id", treats as single dataset. Default is ".id" |
This function creates a bar plot showing the distribution of peaks relative to transcription start sites (TSS), categorizing peaks by their distance from the nearest gene's TSS.
The function performs the following steps:
Categorizes peaks into distance bins based on distanceBreaks
Separates upstream (negative distance) and downstream (positive distance) peaks
Calculates percentages for each distance category
Creates a diverging bar plot with:
Upstream peaks shown as negative bars (left side)
Downstream peaks shown as positive bars (right side)
TSS marked at the center (0)
Distance categories color-coded
Supports grouping by a category column for comparing multiple datasets
A ggplot2 bar plot object showing the distribution of peaks relative to TSS. The plot uses a diverging bar chart format with upstream (5') on the left and downstream (3') on the right, with TSS at the center
Guangchuang Yu https://guangchuangyu.github.io
## Not run: require(TxDb.Hsapiens.UCSC.hg19.knownGene) txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene peakfile <- system.file("extdata", "sample_peaks.txt", package="ChIPseeker") peakAnno <- annotatePeak(peakfile, TxDb=txdb) plotDistToTSS(peakAnno) ## End(Not run)## Not run: require(TxDb.Hsapiens.UCSC.hg19.knownGene) txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene peakfile <- system.file("extdata", "sample_peaks.txt", package="ChIPseeker") peakAnno <- annotatePeak(peakfile, TxDb=txdb) plotDistToTSS(peakAnno) ## End(Not run)
The function is a flexible entry point for plotting peak profiles. It can work with either pre-computed tag matrices or raw peak files/GRanges objects. When provided with peaks, it automatically generates tag matrices and plots them. The function routes to different plotting functions based on the input type and parameters.
plotPeakProf( tagMatrix = NULL, peak, upstream, downstream, conf, by, type, windows_name = NULL, weightCol = NULL, TxDb = NULL, xlab = "Genomic Region (5'->3')", ylab = "Peak Count Frequency", facet = "row", free_y = TRUE, verbose = TRUE, nbin = NULL, ignore_strand = FALSE, ... )plotPeakProf( tagMatrix = NULL, peak, upstream, downstream, conf, by, type, windows_name = NULL, weightCol = NULL, TxDb = NULL, xlab = "Genomic Region (5'->3')", ylab = "Peak Count Frequency", facet = "row", free_y = TRUE, verbose = TRUE, nbin = NULL, ignore_strand = FALSE, ... )
tagMatrix |
matrix or list of matrices, optional. Pre-computed tag matrix
(from |
peak |
peak file (BED format) or GRanges object, or a list of peak
files/GRanges objects for comparing multiple datasets. Required if
|
upstream |
numeric, upstream distance in base pairs. Interpretation
depends on |
downstream |
numeric, downstream distance in base pairs. Interpretation
depends on |
conf |
numeric, confidence level (e.g., 0.95 for 95 confidence intervals are calculated and displayed as ribbons around the average profile. If NA or missing, no confidence intervals are shown. Default varies by function |
by |
character vector, feature(s) of interest. If using TxDb: one of
'gene', 'transcript', 'exon', 'intron', '3UTR', '5UTR', 'UTR'. If using
self-made GRanges: can be any label (used only for plot labels). For
|
type |
character, one of "start_site", "end_site", or "body". Determines
which part of the feature to plot: transcription start site, transcription
end site, or the entire feature body. For |
windows_name |
character vector, optional names for each window (used
in |
weightCol |
character, name of a metadata column in the GRanges object to use as weights for coverage calculation. If NULL, all peaks have equal weight. Default is NULL |
TxDb |
TxDb or EnsDb annotation object, or a list of GRanges objects
containing user-defined genomic features. If a list of GRanges is provided,
each element should correspond to a window defined by |
xlab |
character, x-axis label. Default is "Genomic Region (5'->3')" |
ylab |
character, y-axis label. Default is "Peak Count Frequency" |
facet |
character, one of "none", "row", or "column". Controls how
multiple datasets are displayed: "none" overlays them on the same plot,
"row" creates row facets, "column" creates column facets. Default is "row"
for |
free_y |
logical, if TRUE and faceting is used, y-axis scales independently for each facet. Default is TRUE |
verbose |
logical, whether to print progress messages. Default is TRUE |
nbin |
integer, number of bins for binning mode. If provided, regions are divided into this many equal-sized bins instead of using absolute positions. Useful for comparing features of different lengths. If NULL, uses absolute positions. Default is NULL |
ignore_strand |
logical, whether to ignore strand information when calculating coverage. If FALSE, peaks and features are matched by strand. Default is FALSE |
... |
additional arguments passed to ggplot2 functions for plot customization |
Plot peak profiles around genomic features
This function visualizes the distribution of ChIP-seq peaks around genomic features (e.g., TSS, gene body, exons) by plotting average peak profiles or heatmaps.
The function behavior depends on the input:
If tagMatrix is provided: plots directly from the tag matrix
(supports both normal and binning modes)
If tagMatrix is NULL: generates tag matrix from peaks and routes to:
plotPeakProf2() if by has length 1
plotPeakProf_MultiWindows() if by has length > 1
The function supports:
Single or multiple peak sets (list of peaks)
Confidence intervals for average profiles
Binning mode for large datasets
Faceting options for comparing multiple datasets
TxDb parameter can accept txdb object.
But many regions can not be obtained by txdb object. In this case,
Users can provide self-made granges served the same role
as txdb object and pass to TxDb object.
by the features of interest.
(1) if users use txdb, by can be one of 'gene', 'transcript', 'exon',
'intron' , '3UTR' , '5UTR', 'UTR'. These features can be obtained by functions from txdb object.
(2) if users use self-made granges object, by can be everything. Because this by
will not pass to functions to get features, which is different from the case of using
txdb object. This by is only used to made labels showed in picture.
type means the property of the region. one of the "start site",
"end site" and "body".
upstream and downstream parameter have different usages:
(1) if type == 'body', upstream and downstream can use to extend
the flank of body region.
(2) if type == 'start_site'/'end_site', upstream and downstream refer to
the upstream and downstream of the start_site or the end_site.
weightCol refers to column in peak file. This column acts as a weight value. Details
see https://github.com/YuLab-SMU/ChIPseeker/issues/15
nbin refers to the number of bins. getTagMatrix() provide a binning method
to get the tag matrix.
There are two ways input a list of window.
(1) Users can input a list of self-made granges objects
(2) Users can input a list of by and only one type. In this way,
plotPeakProf_MultiWindows() can made a list of window from txdb object based on by and type.
Warning:
(1) All of these window should be the same type. It means users can only compare a list of "start site"/"end site"/"body region" with the same upstream and downstream.
(2) So it will be only one type and several by.
(3) Users can make window by txdb object or self-made granges object. Users can only
choose one of 'gene', 'transcript', 'exon', 'intron' , '3UTR' , '5UTR' or 'UTR' in the
way of using txdb object. User can input any by in the way of using
self-made granges object.
(4) Users can mingle the by designed for the two ways. plotPeakProf_MultiWindows can
accpet the hybrid by. But the above rules should be followed.
https://github.com/YuLab-SMU/ChIPseeker/issues/189
ggplot object
plot the profile of peaks automatically
plotPeakProf2( peak, upstream, downstream, conf, by, type, weightCol = NULL, TxDb = NULL, xlab = "Genomic Region (5'->3')", ylab = "Peak Count Frequency", facet = "none", free_y = TRUE, verbose = TRUE, nbin = NULL, ignore_strand = FALSE, ... )plotPeakProf2( peak, upstream, downstream, conf, by, type, weightCol = NULL, TxDb = NULL, xlab = "Genomic Region (5'->3')", ylab = "Peak Count Frequency", facet = "none", free_y = TRUE, verbose = TRUE, nbin = NULL, ignore_strand = FALSE, ... )
peak |
peak file (BED format) or GRanges object, or a list of peak files/GRanges objects for comparing multiple datasets |
upstream |
numeric, upstream distance in base pairs. Interpretation
depends on |
downstream |
numeric, downstream distance in base pairs. Interpretation
depends on |
conf |
numeric, confidence level (e.g., 0.95 for 95 confidence intervals are displayed. If NA or missing, no confidence intervals are shown |
by |
character, feature of interest. If using TxDb: one of 'gene', 'transcript', 'exon', 'intron', '3UTR', '5UTR', 'UTR'. If using self-made GRanges: can be any label (e.g., "enhancer", "promoter") used only for plot labels |
type |
character, one of "start_site", "end_site", or "body". Determines which part of the feature to plot |
weightCol |
character, name of a metadata column in the GRanges object to use as weights for coverage calculation. If NULL, all peaks have equal weight. Default is NULL |
TxDb |
TxDb or EnsDb annotation object, or a GRanges object containing user-defined genomic features. Default is NULL |
xlab |
character, x-axis label. Default is "Genomic Region (5'->3')" |
ylab |
character, y-axis label. Default is "Peak Count Frequency" |
facet |
character, one of "none", "row", or "column". Controls how multiple datasets are displayed. Default is "none" |
free_y |
logical, if TRUE and faceting is used, y-axis scales independently for each facet. Default is TRUE |
verbose |
logical, whether to print progress messages. Default is TRUE |
nbin |
integer, number of bins for binning mode. If provided, regions are divided into this many equal-sized bins. If NULL, uses absolute positions. Default is NULL |
ignore_strand |
logical, whether to ignore strand information when calculating coverage. Default is FALSE |
... |
additional arguments passed to ggplot2 functions |
peak stands for the peak file.
by the features of interest.
(1) if users use txdb, by can be one of 'gene', 'transcript', 'exon',
'intron' , '3UTR' , '5UTR', 'UTR'. These features can be obtained by functions from txdb object.
(2) if users use self-made granges object, by can be everything. Because this by
will not pass to functions to get features, which is different from the case of using
txdb object. This by is only used to made labels showed in picture.
type means the property of the region. one of the "start site",
"end site" and "body".
upstream and downstream parameter have different usages:
(1) if type == 'body', upstream and downstream can use to extend
the flank of body region.
(2) if type == 'start_site'/'end_site', upstream and downstream refer to
the upstream and downstream of the start_site or the end_site.
weightCol refers to column in peak file. This column acts as a weight vaule. Details
see https://github.com/YuLab-SMU/ChIPseeker/issues/15
nbin refers to the number of bins, providing a binning method
to get the tag matrix.
TxDb parameter can accept txdb object.
But many regions can not be obtained by txdb object. In this case,
Users can provide self-made granges served the same role
as txdb object and pass to TxDb object.
plotPeakProf2() is different from the plotPeakProf(). plotPeakProf2() do not
need to provide window parameter, which means plotPeakProf2() will call relevent
functions to make window automatically.
ggplot object
G Yu, Ming Li
The function reads tab-delimited peak files and converts them to the specified output format. It automatically detects BED format files based on file extension and handles the coordinate system conversion (BED files use 0-based start coordinates, which are converted to 1-based for R compatibility). Additional columns beyond chromosome, start, and end positions are preserved in the output.
readPeakFile(peakfile, as = "GRanges", ...)readPeakFile(peakfile, as = "GRanges", ...)
peakfile |
character, path to the peak file. Can be a local file path or a URL. Supported formats include BED (.bed, .bed.gz), narrowPeak (.narrowPeak), broadPeak (.broadPeak), gappedPeak (.gappedPeak), bedGraph (.bedGraph.gz), or any tab-delimited file with chromosome, start, and end positions |
as |
character, output format. One of "GRanges" (default) or "data.frame". If "GRanges", returns a GRanges object with additional columns as metadata. If "data.frame", returns a data.frame |
... |
additional parameters passed to |
This function reads peak files in various formats (BED, narrowPeak, broadPeak, etc.) and converts them to either a GRanges object or data.frame. The function automatically handles BED file coordinate conversion (0-based to 1-based).
The function performs the following steps:
Detects file format based on extension (BED files: .bed, .bed.gz, .narrowPeak, .broadPeak, .gappedPeak, .bedGraph.gz, or files ending with Peak.gz)
Reads the file using utils::read.delim() with appropriate
header settings (BED files have no header, other formats may have headers)
Converts BED coordinates from 0-based to 1-based by adding 1 to the start position (BED end position is already exclusive, so no adjustment needed)
Converts to the requested output format (GRanges or data.frame)
Preserves all additional columns beyond the first three (chromosome, start, end) as metadata columns in GRanges or as additional columns in data.frame
Supported file formats include standard BED files, narrowPeak, broadPeak, gappedPeak, bedGraph, and other tab-delimited formats with chromosome, start, and end positions in the first three columns.
Depending on the as parameter:
If as="GRanges": A GRanges object with:
seqnames: Chromosome names (from column 1)
ranges: IRanges with start and end positions (from columns 2 and 3)
Additional metadata columns: All columns beyond the first three are preserved as metadata columns with their original names
If as="data.frame": A data.frame with all columns from the
original file, with BED coordinates converted to 1-based if applicable
G Yu
peakfile <- system.file("extdata", "sample_peaks.txt", package="ChIPseeker") peak.gr <- readPeakFile(peakfile, as="GRanges") peak.gr ## Read a BED file ## peak.gr <- readPeakFile("peaks.bed", as="GRanges") ## Read with custom parameters ## peak.df <- readPeakFile("peaks.txt", as="data.frame", sep="\t")peakfile <- system.file("extdata", "sample_peaks.txt", package="ChIPseeker") peak.gr <- readPeakFile(peakfile, as="GRanges") peak.gr ## Read a BED file ## peak.gr <- readPeakFile("peaks.bed", as="GRanges") ## Read with custom parameters ## peak.df <- readPeakFile("peaks.txt", as="data.frame", sep="\t")
The function renames metadata columns in GRanges objects by converting them to a data.frame, applying the dplyr rename operation, and converting back to GRanges. This allows renaming any metadata column while preserving all genomic range information.
## S3 method for class 'GRanges' rename(x, ...)## S3 method for class 'GRanges' rename(x, ...)
x |
GRanges object to rename columns in |
... |
name-value pairs where the name is the new column name and the
value (unquoted) is the old column name. Syntax: |
This function extends dplyr::rename() to work with GRanges objects,
allowing users to rename metadata columns using familiar dplyr syntax while
preserving the GRanges structure.
The function performs the following steps:
Converts GRanges to data.frame using as.data.frame()
Applies dplyr::rename() with the provided name mappings
Converts back to GRanges using makeGRangesFromDataFrame()
with keep.extra.columns=TRUE
All genomic range information (seqnames, ranges, strand) is preserved. Only metadata columns are renamed; standard GRanges columns (seqnames, start, end, width, strand) cannot be renamed through this function.
GRanges object with renamed metadata columns. All genomic range information and other metadata columns are preserved unchanged
## Not run: ## Rename a single column peak.gr <- peak.gr %>% rename(geneSymbol = SYMBOL) ## Rename multiple columns peak.gr <- peak.gr %>% rename( geneSymbol = SYMBOL, geneName = GENENAME, distance = distanceToTSS ) ## Rename to remove spaces or special characters peak.gr <- peak.gr %>% rename(gene_id = "gene Id") ## End(Not run)## Not run: ## Rename a single column peak.gr <- peak.gr %>% rename(geneSymbol = SYMBOL) ## Rename multiple columns peak.gr <- peak.gr %>% rename( geneSymbol = SYMBOL, geneName = GENENAME, distance = distanceToTSS ) ## Rename to remove spaces or special characters peak.gr <- peak.gr %>% rename(gene_id = "gene Id") ## End(Not run)
The function maps genomic regions to genes through three mechanisms:
Host genes: Regions that overlap with exons or introns of genes. These are genes that directly contain the genomic regions
Proximal genes: Regions located within the promoter region (TSS region) of genes. These are genes whose transcription start sites are near the genomic regions
Flanking genes: Regions located within a specified distance from genes but outside the promoter region. These are nearby genes that may be regulated via cis-regulatory mechanisms
The function returns a vector of unique gene IDs that can be used for downstream functional enrichment analysis (e.g., GO, KEGG, Reactome pathway analysis).
seq2gene(seq, tssRegion, flankDistance, TxDb, sameStrand = FALSE)seq2gene(seq, tssRegion, flankDistance, TxDb, sameStrand = FALSE)
seq |
GRanges object containing genomic regions to be mapped to genes. Typically ChIP-seq peaks, enhancers, or other regulatory elements |
tssRegion |
numeric vector of length 2 specifying the promoter region around the transcription start site (TSS). Default example: c(-1000, 1000) means 1kb upstream and 1kb downstream of TSS. Negative values indicate upstream, positive values indicate downstream. Regions within this range are considered to be in promoter regions |
flankDistance |
numeric, distance in base pairs to search for flanking
genes. Regions that are within this distance from a gene (but outside the
|
TxDb |
TxDb or EnsDb annotation object containing gene/transcript structure information |
sameStrand |
logical, whether to only consider genes on the same strand as the genomic regions when finding overlaps and nearest features. If FALSE, strand is ignored. Default is FALSE |
This function associates genomic regions (e.g., ChIP-seq peaks, enhancers, regulatory elements) with coding genes in a many-to-many mapping. It is designed to link both coding and non-coding genomic regions to coding genes to facilitate functional enrichment analysis.
The function performs the following steps:
Identifies host genes by finding overlaps with exons and introns using
getGenomicAnnotation.internal()
Extracts gene IDs from overlapping exons and introns, converting transcript-based IDs to gene IDs
Finds the nearest gene to each region using
getNearestFeatureIndicesAndDistances()
Categorizes nearest genes into:
Promoter genes: genes where the distance falls within tssRegion
Flanking genes: genes where the absolute distance is less than
flankDistance but outside tssRegion
Combines all gene IDs (host, promoter, and flanking) and returns unique gene IDs
This many-to-many mapping allows a single genomic region to be associated with multiple genes (e.g., overlapping multiple genes or having multiple nearby genes), and a single gene can be associated with multiple genomic regions.
Character vector of unique gene IDs. The vector contains gene IDs from:
Host genes (regions overlapping exons/introns)
Proximal genes (regions within TSS region)
Flanking genes (regions within flankDistance but outside TSS region)
The gene IDs are typically Entrez IDs (for TxDb) or gene_id (for EnsDb),
and can be used directly for functional enrichment analysis with packages
like clusterProfiler, DOSE, or ReactomePA
Guangchuang Yu
annotatePeak for detailed peak annotation,
getNearestFeatureIndicesAndDistances for finding nearest features
## Not run: library(TxDb.Hsapiens.UCSC.hg19.knownGene) TxDb <- TxDb.Hsapiens.UCSC.hg19.knownGene file <- getSampleFiles()[[1]] # a bed file gr <- readPeakFile(file) genes <- seq2gene(gr, tssRegion=c(-1000, 1000), flankDistance = 3000, TxDb) ## Use the gene IDs for enrichment analysis ## library(clusterProfiler) ## ego <- enrichGO(gene = genes, OrgDb = org.Hs.eg.db, ont = "BP") ## End(Not run)## Not run: library(TxDb.Hsapiens.UCSC.hg19.knownGene) TxDb <- TxDb.Hsapiens.UCSC.hg19.knownGene file <- getSampleFiles()[[1]] # a bed file gr <- readPeakFile(file) genes <- seq2gene(gr, tssRegion=c(-1000, 1000), flankDistance = 3000, TxDb) ## Use the gene IDs for enrichment analysis ## library(clusterProfiler) ## ego <- enrichGO(gene = genes, OrgDb = org.Hs.eg.db, ont = "BP") ## End(Not run)
The function generates a null distribution for permutation testing by randomly repositioning peaks within their respective chromosomes. It maintains:
The number of peaks per chromosome
The width of each peak
The chromosome assignment
shuffle(peak.gr, TxDb)shuffle(peak.gr, TxDb)
peak.gr |
GRanges object containing peaks to shuffle |
TxDb |
TxDb or EnsDb annotation object providing chromosome lengths for valid position ranges |
This function randomly shuffles peak positions across chromosomes while preserving the original peak widths and chromosome distribution.
The shuffling process:
Groups peaks by chromosome
For each chromosome, randomly samples new start positions from the valid range (1 to chromosome length - peak width)
Creates new GRanges with shuffled positions but original widths
Sets strand to "*" (unstranded)
This is used in permutation testing to generate null distributions for statistical significance testing.
GRanges object with shuffled peak positions. Peaks are randomly repositioned within their chromosomes, maintaining original widths and chromosome distribution
G Yu
The function allows subsetting of csAnno objects using the same syntax
as subsetting GRanges objects. It filters the peaks in the anno slot
and automatically updates:
The detailGenomicAnnotation data frame to match the filtered peaks
The annoStat annotation statistics
The peakNum total peak count
## S3 method for class 'csAnno' subset(x, ...)## S3 method for class 'csAnno' subset(x, ...)
x |
|
... |
logical expressions indicating which peaks to keep. Can use any
column names from the GRanges metadata (e.g., |
This function subsets a csAnno object by filtering peaks based on
logical conditions, and automatically updates the associated annotation
statistics and detail annotations.
The function:
Creates an index based on chromosome, start, and end positions of all peaks
Subsets the GRanges object in the anno slot using the provided
conditions
Filters the detailGenomicAnnotation data frame to keep only
rows corresponding to the remaining peaks
Recalculates annotation statistics using getGenomicAnnoStat()
Updates the peak count
The tssRegion, level, and hasGenomicAnnotation slots
remain unchanged.
A csAnno object containing only the filtered peaks, with
updated annotation statistics and detail annotations
G Yu
## Not run: ## Subset peaks by annotation type peakAnno_promoter <- subset(peakAnno, annotation == "Promoter") ## Subset peaks by distance to TSS peakAnno_near <- subset(peakAnno, abs(distanceToTSS) < 5000) ## Subset by multiple conditions peakAnno_filtered <- subset(peakAnno, annotation == "Promoter" & abs(distanceToTSS) < 3000) ## End(Not run)## Not run: ## Subset peaks by annotation type peakAnno_promoter <- subset(peakAnno, annotation == "Promoter") ## Subset peaks by distance to TSS peakAnno_near <- subset(peakAnno, abs(distanceToTSS) < 5000) ## Subset by multiple conditions peakAnno_filtered <- subset(peakAnno, annotation == "Promoter" & abs(distanceToTSS) < 3000) ## End(Not run)
plot the heatmap of tagMatrix
tagHeatmap( tagMatrix, xlab = "", ylab = "", title = NULL, palette = "RdBu", nrow = NULL, ncol = NULL )tagHeatmap( tagMatrix, xlab = "", ylab = "", title = NULL, palette = "RdBu", nrow = NULL, ncol = NULL )
tagMatrix |
matrix or list of matrices. Tag matrix with features as rows
and genomic positions as columns, typically obtained from |
xlab |
character, x-axis label. Default is "" (empty) |
ylab |
character, y-axis label. Default is "" (empty) |
title |
character, plot title. If NULL, no title is shown. Default is NULL |
palette |
character, color palette name from RColorBrewer for the heatmap.
See |
nrow |
integer, number of rows for arranging multiple heatmaps when
|
ncol |
integer, number of columns for arranging multiple heatmaps when
|
figure
G Yu
The function creates an UpSet plot (an alternative to Venn diagrams) that shows how peaks are distributed across different combinations of genomic annotations. It displays:
The frequency of each annotation combination (intersection)
Which annotations are present in each combination
Optionally, a vennpie plot overlay showing the overall annotation distribution
upsetplot.csAnno( x, order_by = "freq", vennpie = FALSE, vp = list(x = 0.6, y = 0.7, width = 0.8, height = 0.8) )upsetplot.csAnno( x, order_by = "freq", vennpie = FALSE, vp = list(x = 0.6, y = 0.7, width = 0.8, height = 0.8) )
x |
|
order_by |
character, how to order the intersections in the plot. Options: "freq" (by frequency, default) or "degree" (by number of sets in the intersection). Default is "freq" |
vennpie |
logical, whether to overlay a vennpie plot showing the overall annotation distribution. If TRUE, the vennpie is embedded as a subplot. Default is FALSE |
vp |
list, viewport parameters for positioning the vennpie subplot
when
|
This function visualizes the combinations of genomic annotations (e.g., Promoter, Exon, Intron, UTR) that peaks can have, using an UpSet plot to show set intersections and their frequencies.
The function performs the following steps:
Extracts the detailGenomicAnnotation data frame from the
csAnno object, which contains logical columns indicating
which annotations each peak has
Converts the annotation matrix into a list format where each peak is represented by the set of annotations it has
Creates an UpSet plot using ggupset showing:
Left panel: bar chart of intersection sizes (frequencies)
Top panel: bar chart showing individual set sizes
Bottom panel: matrix showing which sets are included in each intersection
Optionally overlays a vennpie plot if vennpie=TRUE
UpSet plots are particularly useful when there are many annotation categories and peaks can have multiple annotations simultaneously (e.g., a peak can be both in a Promoter and overlap an Exon).
A ggplot2 object (or combined plot if vennpie=TRUE) showing the UpSet visualization. The plot can be further customized using ggplot2 functions or printed directly
Guangchuang Yu
vennpie for the vennpie plot function,
plotAnnoBar for bar plots of annotation distribution
## Not run: require(TxDb.Hsapiens.UCSC.hg19.knownGene) txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene peakfile <- system.file("extdata", "sample_peaks.txt", package="ChIPseeker") peakAnno <- annotatePeak(peakfile, TxDb=txdb) ## Basic UpSet plot upsetplot(peakAnno) ## UpSet plot with vennpie overlay upsetplot(peakAnno, vennpie=TRUE) ## Order by degree instead of frequency upsetplot(peakAnno, order_by="degree") ## End(Not run)## Not run: require(TxDb.Hsapiens.UCSC.hg19.knownGene) txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene peakfile <- system.file("extdata", "sample_peaks.txt", package="ChIPseeker") peakAnno <- annotatePeak(peakfile, TxDb=txdb) ## Basic UpSet plot upsetplot(peakAnno) ## UpSet plot with vennpie overlay upsetplot(peakAnno, vennpie=TRUE) ## Order by degree instead of frequency upsetplot(peakAnno, order_by="degree") ## End(Not run)
The function visualizes the genomic annotation of peaks using a nested pie chart approach. It displays three concentric pie charts showing:
Outer ring: Genic vs Intergenic distribution
Middle ring: Breakdown of Genic (Intron, Exon) and Intergenic (Upstream, Downstream, Distal Intergenic) categories
Inner ring: Further breakdown showing Exon and Downstream regions in detail
This visualization helps understand the overlap between different annotation categories, as peaks can be annotated with multiple features simultaneously.
vennpie(x, r = 0.2, cex = 1.2, ...)vennpie(x, r = 0.2, cex = 1.2, ...)
x |
|
r |
numeric, initial radius for the base pie chart. Controls the overall size of the plot. The nested pies use multiples of this radius (2*r, 3*r, 4*r). Default is 0.2 |
cex |
numeric, character expansion factor for the legend text. Larger values make the legend text bigger. Default is 1.2 |
... |
additional parameters passed to the plotting functions |
This generic function creates a nested pie chart (venn diagram style) visualization showing the distribution of peaks across different genomic annotation categories, with hierarchical nesting to show overlapping annotations.
A plot showing nested pie charts with genomic annotation distribution
plotAnnoBar plotAnnoPie for alternative
visualization methods
The function visualizes the genomic annotation of peaks using a nested pie chart approach. It displays three concentric pie charts showing:
Outer ring: Genic vs Intergenic distribution
Middle ring: Breakdown of Genic (Intron, Exon) and Intergenic (Upstream, Downstream, Distal Intergenic) categories
Inner ring: Further breakdown showing Exon and Downstream regions in detail
This visualization helps understand the overlap between different annotation categories, as peaks can be annotated with multiple features simultaneously (e.g., a peak can be both in an Exon and in a Promoter region).
vennpie.csAnno(x, r = 0.2, cex = 1.2, col = NULL)vennpie.csAnno(x, r = 0.2, cex = 1.2, col = NULL)
x |
|
r |
numeric, initial radius for the base pie chart. Controls the overall size of the plot. The nested pies use multiples of this radius (2*r, 3*r, 4*r). Default is 0.2 |
cex |
numeric, character expansion factor for the legend text. Larger values make the legend text bigger. Default is 1.2 |
col |
named character vector, custom colors for annotation categories. Names should match category names: "Genic", "Intergenic", "Intron", "Exon", "Upstream", "Downstream", "Distal_Intergenic". Colors not specified will use default colors. Default is NULL (uses default color scheme) |
This function creates a nested pie chart (venn diagram style) visualization showing the distribution of peaks across different genomic annotation categories, with hierarchical nesting to show overlapping annotations.
The function performs the following steps:
Extracts detailed genomic annotation from the csAnno object
Calculates counts for each annotation category:
Genic: peaks overlapping exons or introns
Intergenic: peaks not in genic regions
Exon: peaks overlapping exons
Intron: peaks overlapping introns
Upstream: peaks in promoter regions with negative distance to TSS
Downstream: peaks downstream of genes
Distal Intergenic: intergenic peaks far from genes
Creates three nested floating pie charts using floating.pie()
from the plotrix package
Adds a legend showing all annotation categories with their colors
The function uses pseudo-counts (+1) for each category to ensure proper visualization even when some categories have zero counts, preventing color mismatches in the pie charts.
No return value. Creates a plot showing nested pie charts of genomic annotation distribution
G Yu
plotAnnoPie for a simple pie chart,
plotAnnoBar for a bar chart visualization
## Not run: require(TxDb.Hsapiens.UCSC.hg19.knownGene) txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene peakfile <- system.file("extdata", "sample_peaks.txt", package="ChIPseeker") peakAnno <- annotatePeak(peakfile, TxDb=txdb) ## Create venn pie chart vennpie(peakAnno) ## Customize colors vennpie(peakAnno, col=c(Exon="red", Intron="blue")) ## Adjust size and legend vennpie(peakAnno, r=0.3, cex=1.5) ## End(Not run)## Not run: require(TxDb.Hsapiens.UCSC.hg19.knownGene) txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene peakfile <- system.file("extdata", "sample_peaks.txt", package="ChIPseeker") peakAnno <- annotatePeak(peakfile, TxDb=txdb) ## Create venn pie chart vennpie(peakAnno) ## Customize colors vennpie(peakAnno, col=c(Exon="red", Intron="blue")) ## Adjust size and legend vennpie(peakAnno, r=0.3, cex=1.5) ## End(Not run)
The function calculates all possible intersections between sets using the
overlap() function, then visualizes the results as a Venn diagram.
It supports three plotting backends, each with different features:
gplots: Default method, produces simple black-and-white Venn
diagrams using the gplots package
ggVennDiagram: Produces colorful, customizable Venn diagrams
using ggplot2, allowing full control over colors, labels, and styling
Vennerable: Alternative method using the Vennerable package
(requires installation from R-Forge)
vennplot(Sets, by = "gplots", ...)vennplot(Sets, by = "gplots", ...)
Sets |
named list of objects to compare. Each element can be:
If the list is not named, names will be auto-generated as "Set1", "Set2", etc. |
by |
character, plotting method to use. One of:
|
... |
additional parameters passed to
See |
This function creates Venn diagrams to visualize overlaps between multiple sets of objects (e.g., peaks, genes, genomic regions). It supports three different plotting methods with different features and customization options.
The function performs the following steps:
Validates input: ensures the list is named (auto-generates names if missing, e.g., "Set1", "Set2", ...)
Calculates all possible intersections using overlap(), which
handles both vectors and GRanges objects
Creates the Venn diagram using the specified method:
gplots: Uses plot.venn() with a matrix format
ggVennDiagram: Passes sets directly to
ggVennDiagram::ggVennDiagram() with additional parameters
Vennerable: Creates a Venn object and plots it
For GRanges objects, the function uses set intersection to find overlapping genomic regions. For vectors, it uses standard set intersection.
A Venn diagram plot. The return type depends on the by parameter:
gplots: Base R plot (invisible return)
ggVennDiagram: ggplot2 object that can be further customized
Vennerable: Grid plot (invisible return)
G Yu
overlap for calculating set intersections,
vennplot.peakfile for a convenience function for peak files
## Not run: require(TxDb.Hsapiens.UCSC.hg19.knownGene) txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene peakfiles <- getSampleFiles() peakAnnoList <- lapply(peakfiles, annotatePeak, TxDb=txdb) names(peakAnnoList) <- names(peakfiles) ## Compare genes from different peak files genes <- lapply(peakAnnoList, function(i) as.data.frame(i)$geneId) vennplot(genes) ## Use ggVennDiagram for customizable plot vennplot(genes, by="ggVennDiagram", show_percentage=TRUE) ## Compare GRanges objects directly peaks <- lapply(peakfiles, readPeakFile) names(peaks) <- names(peakfiles) vennplot(peaks) ## End(Not run)## Not run: require(TxDb.Hsapiens.UCSC.hg19.knownGene) txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene peakfiles <- getSampleFiles() peakAnnoList <- lapply(peakfiles, annotatePeak, TxDb=txdb) names(peakAnnoList) <- names(peakfiles) ## Compare genes from different peak files genes <- lapply(peakAnnoList, function(i) as.data.frame(i)$geneId) vennplot(genes) ## Use ggVennDiagram for customizable plot vennplot(genes, by="ggVennDiagram", show_percentage=TRUE) ## Compare GRanges objects directly peaks <- lapply(peakfiles, readPeakFile) names(peaks) <- names(peakfiles) vennplot(peaks) ## End(Not run)
The function simplifies the workflow of comparing multiple peak files by
automatically reading the files and setting up the Venn diagram. It loads
each peak file using readPeakFile(), optionally labels them, and then
calls vennplot() to create the visualization.
vennplot.peakfile(files, labels = NULL)vennplot.peakfile(files, labels = NULL)
files |
character vector of peak file paths. Supported formats include
BED, narrowPeak, broadPeak, and other formats supported by
|
labels |
character vector of labels for each peak file. If NULL, labels are automatically generated from filenames by removing file extensions. Default is NULL |
This is a convenience function that reads peak files and creates a Venn diagram showing the overlap of genomic regions between different peak sets.
The function:
Reads each peak file using readPeakFile() (converts to GRanges)
Generates labels from filenames if not provided (removes file extensions)
Names the peak list with the labels
Calls vennplot() to create the Venn diagram
This is particularly useful for quickly comparing multiple ChIP-seq peak files to see how many peaks are shared between experiments.
A Venn diagram plot showing the overlap of peaks between different
files. The plot is created using the default method (by="gplots").
See vennplot for details on the return type
G Yu
vennplot for the main plotting function,
readPeakFile for reading peak files
## Not run: ## Compare multiple peak files peakfiles <- c("sample1.bed", "sample2.bed", "sample3.bed") vennplot.peakfile(peakfiles) ## With custom labels vennplot.peakfile(peakfiles, labels=c("Treatment", "Control", "Input")) ## Using getSampleFiles() files <- getSampleFiles() vennplot.peakfile(files) ## End(Not run)## Not run: ## Compare multiple peak files peakfiles <- c("sample1.bed", "sample2.bed", "sample3.bed") vennplot.peakfile(peakfiles) ## With custom labels vennplot.peakfile(peakfiles, labels=c("Treatment", "Control", "Input")) ## Using getSampleFiles() files <- getSampleFiles() vennplot.peakfile(files) ## End(Not run)