Skip to main content
v2026.11,986 entries · CC-BY 4.0

pyBigWig: Read and Write bigWig and bigBed Files in Python

How to install pyBigWig, query bigWig and bigBed files from Python, and avoid the 0-based coordinate and missing-data traps, with a tested example.

Written and maintained by CASRAI Editorial Board

Published

On this page

pyBigWig is a Python extension, written in C, that reads bigBed files and both reads and creates bigWig files, so a researcher can pull signal values for a genomic region straight into a script instead of converting the whole file to text first. It is maintained by the deepTools project and installed with pip install pyBigWig or from the bioconda channel. This guide covers what it does, installation, a tested end-to-end example, how to interpret what it returns, and the coordinate and missing-data traps that most often produce wrong numbers.

What pyBigWig is used for in research

A bigWig file stores dense, continuous values along a genome, such as read coverage, ChIP-seq or ATAC-seq signal, mappability or conservation scores. UCSC describes it as an indexed binary format in which only the portions needed to display a region are transferred, which is why it is faster than a plain wiggle file on large data sets. A bigBed file does the same for annotation items that a BED file would hold, such as peaks or exons. pyBigWig gives Python programs the same region-level access, locally or over a URL.

Typical uses are extracting the signal under a set of peaks or promoters, summarising a track in fixed bins, checking a result before plotting it in a browser such as IGV, and writing a computed signal track (for example a normalised coverage track) back out as a bigWig. Data from a ChIP-seq pipeline is a common source of such tracks. The wider Python toolchain for this kind of work is outlined in Python for bioinformatics.

The library has three layers of access. values() returns one number per base. intervals() returns the stored intervals themselves. stats() returns summaries over a region, optionally split into bins. For bigBed files, entries() returns intervals with their attached text. The same pyBigWig.open() call returns the same kind of object for both formats.

How to install or access pyBigWig

The project README gives two official routes:

  1. With pip: pip install pyBigWig
  2. With conda: conda install pybigwig -c conda-forge -c bioconda

Building from source needs the headers and libraries for libcurl (with its curl-config tool) and zlib. The PyPI page lists the MIT licence and a requirement of Python 3.9 or later. Two build-time details change what the installed package can do, and both can be checked from Python after installation:

  • Remote files. If curl was not available when the package was built, pyBigWig installs without the ability to open remote files. pyBigWig.remote returns 1 when remote access works and 0 when it does not.
  • NumPy support. NumPy must be installed before pyBigWig for NumPy integers and vectors to be accepted. pyBigWig.numpy returns 1 when the package was compiled with it.

If you manage environments with conda, installing from the two channels above into a dedicated environment keeps these build dependencies consistent; see the guide on conda-forge for how that channel behaves. pyBigWig is also packaged for Galaxy, according to the README.

How to read and write a bigWig file with pyBigWig step by step

The steps below create a small bigWig, then query it. The values are a toy illustration chosen so the arithmetic can be checked by hand, not real data, and the outputs shown were produced by running exactly these commands.

  1. Import the module. import pyBigWig
  2. Open a file for writing. bw = pyBigWig.open("toy.bw", "w"). A file opened for writing cannot be queried; it can only be written to.
  3. Add the header. The header lists every chromosome with its length, in the order the file will use, and must be added before any entries: bw.addHeader([("chr1", 1000000), ("chr2", 1500000)]). Chromosome names are case-sensitive, so chr1 and Chr1 differ, and 1 is not chr1.
  4. Add entries in sorted order. This example uses the bedGraph-like layout, with parallel lists of chromosomes, starts, ends and values: bw.addEntries(["chr1","chr1","chr1"], [0,100,125], ends=[100,120,126], values=[0.0,1.0,200.0]). Two other layouts exist: variable step with a fixed span, and fixed step with a fixed span. Per the README, entries must be in order, and validate=False skips the order check at your own risk.
  5. Close the file. bw.close(). This is not optional for writing: closing flushes buffered entries, builds the index and constructs the zoom levels, and it can take time on large files.
  6. Reopen for reading. bw = pyBigWig.open("toy.bw"). Reading is the default mode. If the path does not exist, open() prints an error and returns None, so test the result before using it.
  7. Confirm the type and chromosomes. bw.isBigWig() returns True; bw.chroms() returns {'chr1': 1000000, 'chr2': 1500000}.
  8. Query a region. Each call takes the chromosome, start and end:
    bw.stats("chr1", 90, 130)                 # [7.096774193548387]
    bw.stats("chr1", 90, 130, type="max")     # [200.0]
    bw.stats("chr1", 90, 130, type="coverage")# [0.775]
    bw.stats("chr1", 90, 130, nBins=2, exact=True)  # [0.5, 19.09090909090909]
    bw.values("chr1", 118, 127)               # [1.0, 1.0, nan, nan, nan, nan, nan, 200.0, nan]
    bw.intervals("chr1", 90, 130)             # ((0, 100, 0.0), (100, 120, 1.0), (125, 126, 200.0))

To start from existing text files instead, UCSC documents the conversion tools: bedGraphToBigWig in.bedGraph chrom.sizes out.bw for sparse or variable-size data, and wigToBigWig input.wig chrom.sizes myBigWig.bw for continuous, equally sized wiggle data (one track per file, gzipped input accepted). The chrom.sizes file can be produced with UCSC’s fetchChromSizes script. For a UCSC-hosted assembly it can also be a URL.

For bigBed, open the file the same way and call entries(). The README example opens an ENCODE bigBed by URL and runs bb.entries("chr1", 10000000, 10020000), which returns tuples of start, end and a tab-separated string; bb.SQL() returns the field definitions needed to parse that string, and withString=False returns positions only to save memory.

How to read the output

Each of the example calls above shows a different behaviour worth understanding before you trust a number.

Mean, maximum, coverage and standard deviation

The default stats() type is the mean over bins (nBins defaults to 1). The other options are max, min, coverage (the fraction of bases that have a value) and std. In the toy file the region 90 to 130 spans 40 bases, but only 31 carry a value: 10 bases at 0.0, 20 at 1.0 and 1 at 200.0. The sum is 220, and 220 divided by 31 gives the reported mean of 7.0968. The coverage of 0.775 is 31 divided by 40. Dividing 220 by 40 would give 5.5, which is what you would get by treating the uncovered bases as zero.

That is the first trap. The README states that for type="mean", bases without a value are excluded from the denominator. If you want a mean over the whole interval with missing bases counted as zero, take values() and replace NaN with zero before averaging.

Missing bases come back as NaN

values() always returns one entry per base in the range, with nan where the file has no value. In the example, positions 120 to 124 have no entry and appear as NaN. Downstream arithmetic then needs NaN-aware functions; the guide on NumPy NaN handling covers the usual options. With NumPy support compiled in, values(..., numpy=True) returns an array directly.

Approximate versus exact summaries

The README explains that bigWig files carry precomputed zoom levels, built for fast browsing. When you request a summary, pyBigWig follows the same rule as Kent’s tools: it uses the zoom level with the largest bins no wider than half the requested interval, and falls back to the original intervals when none qualifies. The result can therefore be approximate. The README’s own example shows the difference on an ENCODE mappability track: the default stats() gave 0.2012, while the mean of values() and stats(..., exact=True) both gave 0.2221. Use exact=True when you need exact mean, maximum or similar, accepting a small cost in speed.

Intervals are returned whole

In the example, asking for 90 to 130 returned the interval (0, 100, 0.0), not a version trimmed to start at 90. Intervals that overlap the query are returned as stored, so clip them yourself if your analysis needs exact boundaries.

The header dictionary

bw.header() returns the version, number of zoom levels (nLevels), nBasesCovered, minVal, maxVal, sumData and sumSquared. The last two are what a program needs for a whole-file mean and standard deviation. In the toy file they are 220 and 40020, matching 0, 20 and 40000 contributions from the three entries.

Coordinates

Wiggle, bigWig and bigBed use 0-based, half-open coordinates, and pyBigWig follows them. The first base of a chromosome is start 0, end 1, and the README gives bases 100 to 115 (1-based, inclusive) as start 99, end 115. A query that seems off by one is almost always this; the guide on BED coordinates and the 0-based convention explains the same convention in BED files.

Troubleshooting pyBigWig

  • open() returns None. The file does not exist or cannot be read. The function prints an error and returns None rather than raising, so a later call fails on None.
  • Remote URLs do not open. Check pyBigWig.remote. A value of 0 means the package was built without libcurl. Install the curl headers and reinstall, or use the conda package.
  • NumPy arguments are rejected or numpy=True does nothing. Check pyBigWig.numpy. NumPy must have been installed before pyBigWig.
  • No values for a chromosome you know exists. Chromosome names are case-sensitive and 1 is not chr1. Compare against bw.chroms(). You cannot mix Ensembl-style and UCSC-style names.
  • Cannot query a file just written. A file opened with mode "w" can only be written to. Close it and reopen it for reading.
  • Written file is unusable elsewhere. Entries must be in order, and the header chromosome order is the file order. Setting maxZooms=0 in addHeader() produces a file with no zoom levels, which the README warns IGV and many other tools will not read.
  • Empty file returns odd results. For a bigWig with no entries, intervals() returns None, stats() returns a list of None and values() returns an empty list. The README notes that such files are generally not compatible with other programs.
  • Means look too high. Missing bases are excluded from the mean denominator; see the section on reading the output.

Free alternatives to pyBigWig

Each row below is limited to what the cited documentation states.

Tool What it does with bigWig or bigBed Source
bigWigSummary (UCSC) Extracts summary information from a bigWig file UCSC bigWig help
bigWigAverageOverBed (UCSC) Computes the average score of a bigWig over each BED record, which may have introns UCSC bigWig help
bigWigToBedGraph and bigWigToWig (UCSC) Convert a bigWig back to bedGraph or wig text UCSC bigWig help
bigWigInfo (UCSC) Prints information about a bigWig file UCSC bigWig help
bedGraphToBigWig, wigToBigWig, bedToBigBed (UCSC) Create bigWig or bigBed files from text formats UCSC bigWig and bigBed help
libBigWig The C library pyBigWig uses for local and remote file access pyBigWig README
Galaxy package pyBigWig available inside Galaxy pyBigWig README

The UCSC utilities accept file paths or URLs and suit one-off command-line jobs, while pyBigWig suits cases where the values feed straight into Python analysis. The UCSC utilities are downloaded from the UCSC binary utilities directory.

Frequently asked questions

What is pyBigWig?

pyBigWig is a Python extension written in C for fast access to bigBed files and for reading and creating bigWig files, using the libBigWig library for local and remote access.

Can pyBigWig create bigBed files?

The documentation describes bigBed support as read access, local or remote, through entries(). Writing is documented for bigWig only. To create a bigBed, UCSC documents the bedToBigBed program.

Does pyBigWig use 0-based or 1-based coordinates?

0-based and half-open, the same as the underlying file formats. The first base of a chromosome is start 0, end 1.

Why does stats() differ from the mean of values()?

By default stats() may use precomputed zoom levels and so can be approximate, and it excludes missing bases from the denominator. Use exact=True for exact summaries, and replace NaN with zero in values() if missing bases should count as zero.

Sources

Data: pyBigWig query methods: what each returns and how it treats missing data

Compiled from the pyBigWig README and PyPI page: the main read and write methods, the arguments that change their results, and how each behaves on missing bases or sorted-order constraints.

pyBigWig query methods: what each returns and how it treats missing data
MethodReturnsKey argumentsBehaviour to note
open(path, mode)File object for bigWig or bigBed; None if the file is missingmode: read by default, w to writeMode is ignored for bigBed; a file opened with w cannot be queried
header()Dict: version, nLevels, nBasesCovered, minVal, maxVal, sumData, sumSquarednonesumData and sumSquared support whole-file mean and standard deviation
chroms([name])Dict of chromosome lengths, or one lengthoptional chromosome nameNothing is output for a non-existent chromosome name
values(chrom, start, end)One value per base in the rangenumpy=True for an arraynan where a base has no value
stats(chrom, start, end)List of summaries, one per bintype: mean (default), max, min, coverage, std; nBins (default 1); exactMean excludes bases with no value from the denominator; default may use zoom levels so exact=True gives exact results
intervals(chrom, start, end)Tuples of (start, end, value)start and end optional (whole chromosome)Returns None for a bigWig file with no entries
entries(chrom, start, end)bigBed tuples of (start, end, string)withString=False for positions onlyParse the string using SQL()
addHeader(list_of_chrom_length, maxZooms)None (must precede entries)maxZooms: up to 10 by defaultmaxZooms=0 files may not work in IGV and other tools
addEntries(chroms, starts, ends, values, span, step, validate)NoneThree layouts: bedGraph-like, variable step with span, fixed step with spanEntries must be in order; validate=False skips the check
close()NonenoneRequired in write mode: flushes entries, builds the index and zoom levels

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about pyBigWig: Read and Write bigWig and bigBed Files in Python

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →