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

pandas plot Guide: Syntax, Methods & Charts

Learn pandas plot syntax, customize line and bar charts with Matplotlib axes, set secondary y-axes, and troubleshoot common Python visualization errors.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

What it is used for in research

For empirical researchers, data analysts, and laboratory scientists, pandas.DataFrame.plot and pandas.Series.plot provide a direct, high-level interface to visualize structured experimental datasets without writing verbose low-level rendering code. Built as an expressive abstraction layer on top of Matplotlib, the plotting accessor enables researchers to transform tabular experimental observations directly into publication-quality line graphs, bar charts, histograms, scatter plots, and box plots.

In scientific computing, exploratory data analysis requires rapid iteration between data wrangling and graphical inspection. Researchers tracking longitudinal assay readings, sensor telemetry, genomic variant distributions, or survey responses rely on pandas to manage tabular structures. When researchers prepare data pipelines using routines such as pandas add column to calculate derived metrics or pandas isin filtering to isolate specific experimental cohorts, invoking .plot() immediately visualizes trends while automatically preserving index alignments, column names, and series metadata.

While specialized statistical libraries such as a Seaborn histogram provide high-level distribution modeling and specialized routines construct a custom bar plot in Matplotlib, the pandas plotting API bridges the gap by coupling data manipulation with visualization. As explored in the Seaborn vs Matplotlib and Plotly vs Matplotlib comparisons, pandas acts as a versatile workflow hub, supporting both static figure generation for academic manuscripts and dynamic backend switching for interactive data exploration.

How to install or access it

Pandas is distributed officially through the Python Package Index (PyPI) and the Conda package ecosystem under an open-source BSD 3-Clause license. The core .plot accessor relies on Matplotlib as its default graphic rendering engine.

Current versions (pandas 2.x) require a 64-bit Python environment running Python 3.9 or newer, alongside Matplotlib version 3.6.1 or higher for default rendering. Install both packages using official package manager commands:

# Installation via PyPI
pip install pandas matplotlib

# Installation via Conda Forge
conda install -c conda-forge pandas matplotlib

Verify that both libraries are installed and check their active versions in your scientific computing environment:

import pandas as pd
import matplotlib as mpl

print(f"pandas version: {pd.__version__}")
print(f"matplotlib version: {mpl.__version__}")

The authoritative function signature from the official pandas API documentation is:

DataFrame.plot(
    x=None,
    y=None,
    kind='line',
    ax=None,
    subplots=False,
    sharex=None,
    sharey=False,
    layout=None,
    figsize=None,
    use_index=True,
    title=None,
    grid=None,
    legend=True,
    style=None,
    logx=False,
    logy=False,
    loglog=False,
    xticks=None,
    yticks=None,
    xlim=None,
    ylim=None,
    rot=None,
    fontsize=None,
    colormap=None,
    table=False,
    yerr=None,
    xerr=None,
    secondary_y=False,
    **kwargs
)

Pandas supports two syntactical conventions for specifying visualization types: passing the chart format into the kind parameter (such as df.plot(kind='scatter', x='time', y='response')) or invoking dedicated plot accessor methods directly (such as df.plot.scatter(x='time', y='response')). Supported plot kinds include 'line', 'bar', 'barh', 'hist', 'box', 'kde', 'density', 'area', 'pie', 'scatter', and 'hexbin'.

Step-by-step instructions

The following numbered procedure demonstrates how to load longitudinal experimental assay data, plot multi-variable trends with dual y-axes, integrate scientific error bars, and embed the visualization into a multi-panel Matplotlib figure layout.

  1. Construct the research dataset with aligned experimental indexes.
    Simulate a laboratory bioreactor trial measuring bacterial culture optical density (absorbance at 600 nm, OD600) and medium pH over a 12-hour incubation period across control and treatment conditions:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    # Generate reproducible longitudinal assay data
    time_hours = np.arange(0, 13, 1)
    data = {
        "time_hours": time_hours,
        "od600_control": np.array([0.05, 0.08, 0.14, 0.28, 0.55, 0.89, 1.25, 1.52, 1.68, 1.74, 1.76, 1.77, 1.77]),
        "od600_treated": np.array([0.05, 0.07, 0.11, 0.19, 0.35, 0.62, 0.94, 1.18, 1.35, 1.42, 1.45, 1.46, 1.46]),
        "od600_sem": np.array([0.01, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.05, 0.04, 0.03, 0.02, 0.02, 0.02]),
        "culture_ph": np.array([7.20, 7.18, 7.12, 7.01, 6.82, 6.55, 6.28, 6.05, 5.88, 5.76, 5.70, 5.68, 5.67])
    }
    
    df_assay = pd.DataFrame(data).set_index("time_hours")
    print(df_assay.head(3))
    
  2. Generate a baseline comparative line plot.
    Call .plot() on selected numeric columns. By default, pandas maps the DataFrame index (elapsed time in hours) to the horizontal axis:

    # Render comparative growth kinetics
    ax = df_assay[["od600_control", "od600_treated"]].plot(
        kind="line",
        figsize=(8, 5),
        title="Bacterial Growth Kinetics (OD600)",
        grid=True,
        style=["o-", "s--"]
    )
    ax.set_xlabel("Incubation Time (hours)")
    ax.set_ylabel("Optical Density (OD600)")
    
  3. Plot disparate variables simultaneously using a secondary y-axis.
    When tracking variables with different measurement units or numerical scales (such as cell density ranging from 0.0 to 2.0 and pH ranging from 5.5 to 7.5), assign the second variable to secondary_y:

    # Plot optical density on primary axis and pH on secondary axis
    ax = df_assay[["od600_control", "culture_ph"]].plot(
        secondary_y=["culture_ph"],
        figsize=(8, 5),
        title="Culture Growth vs. Medium pH Acidification",
        grid=True
    )
    ax.set_ylabel("Optical Density (OD600)")
    ax.right_ax.set_ylabel("Medium pH")
    
  4. Incorporate experimental error bars using yerr.
    Pass standard error of the mean (SEM) or standard deviation columns into the yerr argument to depict measurement variability faithfully:

    # Add symmetric error bars representing standard error
    ax = df_assay[["od600_control"]].plot(
        yerr=df_assay["od600_sem"],
        capsize=4,
        figsize=(8, 5),
        title="Control Growth Curve with Standard Error Bars",
        color="#1f77b4"
    )
    ax.set_ylabel("Optical Density (OD600)")
    
  5. Assemble a multi-panel publication figure using Matplotlib subplots.
    Pass existing Matplotlib Axes instances into the ax parameter to construct customized, publication-grade figures:

    # Initialize a 1-row, 2-column figure layout
    fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(12, 5))
    
    # Render growth trajectories on panel 1
    df_assay[["od600_control", "od600_treated"]].plot(
        ax=ax1,
        title="(A) Growth Curves",
        style=["b-", "r--"]
    )
    ax1.set_xlabel("Time (h)")
    ax1.set_ylabel("OD600")
    
    # Render pH trajectory on panel 2
    df_assay[["culture_ph"]].plot(
        ax=ax2,
        title="(B) Medium Acidification",
        color="darkgreen"
    )
    ax2.set_xlabel("Time (h)")
    ax2.set_ylabel("pH")
    
    plt.tight_layout()
    fig.savefig("bioreactor_analysis.pdf", dpi=300, bbox_inches="tight")
    plt.show()
    

Output and how to read it

The return value of df.plot() depends directly on whether subplots are requested in the call:

  • Single plot call (default, subplots=False): Returns a single matplotlib.axes.Axes object. Researchers can invoke all standard Matplotlib methods on this handle—such as ax.set_ylim(), ax.axhline(), ax.annotate(), or ax.legend()—to customize axis bounds, statistical threshold lines, and annotation labels.
  • Multi-panel call (subplots=True): Returns an ndarray of matplotlib.axes.Axes objects corresponding to each rendered panel. When layout=(nrows, ncols) is specified, the returned array preserves the 2D grid geometry, allowing iteration across rows and columns.
  • Dual-axis plots (secondary_y=True): Returns the primary left-hand Axes object, which stores a reference to the right-hand secondary axis accessible via ax.right_ax. Both axes must be labeled separately to maintain clear visual differentiation between distinct units of measurement.

When inspecting graphical output in an empirical research pipeline, check three visual validation points:

  • Axis scales and tick labels: Confirm whether logarithmic scaling (logy=True or logx=True) is required to represent exponential physical processes such as microbial growth, serial dilution assays, or acoustic decibels.
  • Legend completeness: Ensure series legends accurately describe experimental treatments rather than generic column indexes, avoiding ambiguous labels in multi-condition plots.
  • Export resolution: For academic manuscripts and technical reports, export the underlying figure via fig.savefig() using vector formats (PDF or SVG) or high-resolution raster formats (minimum 300 DPI PNG) to prevent pixelation during publication printing.

Troubleshooting

When executing plotting calls in automated data pipelines, unexpected data structures, type mismatches, or missing graphics dependencies will raise runtime exceptions. The table below lists verified diagnostic causes and solutions for common pandas.plot errors:

Error Message Root Cause Diagnostic & Remediation
TypeError: no numeric data to plot The DataFrame or selected subset contains only non-numeric data types (strings, object columns, or unparsed categories). Inspect column data types using df.dtypes. Convert numeric columns with string representations using df[col] = pd.to_numeric(df[col], errors='coerce').
ValueError: scatter requires x and y to be column names In scatter plots (kind='scatter'), x and y arguments must explicitly name existing columns, not index names or raw arrays. If the intended horizontal variable is currently stored as the DataFrame index, call df.reset_index().plot.scatter(x='index_col', y='val_col').
ImportError: matplotlib is required for plotting when the default backend is selected Matplotlib is not installed in the active Python virtual environment. Install the official Matplotlib rendering engine via pip install matplotlib or conda install -c conda-forge matplotlib.
ValueError: Could not find backend '...' A plotting backend specified via pd.set_option('plotting.backend', ...) or the backend parameter is not installed or misnamed. Verify that the requested backend package (such as plotly or hvplot) is installed in the environment, or reset to default using pd.set_option('plotting.backend', 'matplotlib').
Distorted time-series x-axis tick labels and uneven spacing The horizontal index consists of raw date strings rather than a structured pandas.DatetimeIndex. Parse date strings into proper temporal timestamps using df.index = pd.to_datetime(df.index) before calling .plot() to enable automatic date formatting.

Free alternatives

Researchers evaluating graphical libraries for scientific and statistical computing have access to multiple free, open-source visualization packages across Python and R:

Library / Tool Ecosystem Grammar & Design Paradigm Primary Research Strength Interactive Capability Primary License
pandas plot Python DataFrame method wrapper around Matplotlib Fast exploratory data inspection directly coupled with tabular transformations Static (Matplotlib) or Interactive (via Plotly backend) BSD 3-Clause
Matplotlib Python Imperative / object-oriented canvas drawing Fine-grained layout, custom figure geometry, and exact typography control for print Primarily static; interactive zoom/pan in local GUI windows PSF / Custom BSD-compatible
Seaborn Python Declarative statistical visualization wrapper Automated aggregation, confidence interval shading, and multi-variable facet grids Static raster and vector rendering BSD 3-Clause
Plotly Express Python, R, Julia Declarative Grammar of Graphics for the web Interactive pan, zoom, hover tooltips, and web dashboard integration Fully interactive HTML/WebGL outputs MIT License
plotnine Python Grammar of Graphics (strict ggplot2 port) Layered aesthetic mappings and facet specifications matching R workflows Static rendering via Matplotlib backend MIT License
R ggplot2 R Strict Grammar of Graphics Comprehensive statistical publication graphics with extensive academic ecosystem Static (interactive via plotly::ggplotly) MIT License

FAQ

What is the difference between df.plot() and invoking matplotlib.pyplot directly?

Calling df.plot() provides an automated, high-level wrapper around Matplotlib. It automatically maps the DataFrame index to the horizontal axis, assigns column headers to legend labels, formats date indexes, and handles multi-column grouping in a single command. Direct Matplotlib calls (plt.plot()) require manually extracting NumPy arrays, explicitly defining legend handles, and writing boilerplate loop code to plot multiple columns.

How do I display multiple numeric columns in individual subplots?

Pass subplots=True to the plotting function. You can control the multi-panel grid layout by supplying a row and column tuple to the layout argument, such as df.plot(subplots=True, layout=(2, 2), figsize=(10, 8)). To decouple horizontal or vertical scales across panels, set sharex=False or sharey=False.

Can pandas plot create interactive charts without rewriting code?

Yes. Starting in pandas 0.25+, the plotting backend is pluggable. By installing Plotly (pip install plotly) and setting the global option pd.set_option('plotting.backend', 'plotly'), subsequent calls to df.plot() render interactive HTML/JavaScript figures supporting hover inspections, panning, and dynamic box zooming while using standard pandas syntax.

How do I customize error bars on a pandas bar or line chart?

Pass an array, a list, or the name of a DataFrame column to the yerr (or xerr) parameter. For symmetric error bars across all data points, pass a Series containing standard deviations or standard errors: df['mean'].plot(kind='bar', yerr=df['sem'], capsize=4). For asymmetric confidence intervals, supply a two-dimensional array of shape (2, N) representing lower and upper error bounds.

Why does df.plot.scatter() raise an error when I pass the DataFrame index as x?

The scatter method strictly requires x and y to be string column names present within the DataFrame table. If the independent variable is currently assigned as the DataFrame index, call df.reset_index().plot.scatter(x='index_col', y='target_col') to elevate the index into a standard named column before plotting.

Sources

Follow CASRAI

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

Ask CASRAI · full access

Ask about pandas plot Guide: Syntax, Methods & Charts

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 →