Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 57 ยท Saving and Production

The Matplotlib Ecosystem

See how seaborn, plotly, bokeh, altair, plotnine, cartopy, mplfinance and pandas plotting relate to Matplotlib, and how to choose the right tool.

Matplotlib is not the only plotting library in Python, and it was never meant to be. It is the foundation that many other libraries stand on, and a few are rivals with a different design. Knowing the landscape saves you from two mistakes: reinventing a chart that a specialized library gives you in one line, and switching libraries when a small Matplotlib tweak would have solved the problem.

This lesson maps the ecosystem. Libraries built on Matplotlib (seaborn, plotnine, cartopy, mplfinance, pandas plotting) give you its output and its customization. Libraries with their own engines (plotly, bokeh, altair) make interactive charts for the web. Only the pandas examples can run on this site; the others are shown as read-only code, so you can recognize them and judge when to use them. You will need the basics from Plotting NumPy and pandas Data and Seaborn-Style Recipes in Pure Matplotlib.

Built on Matplotlib

seaborn Statistical charts from DataFrames.
plotnine Grammar of graphics, like ggplot2.
cartopy Maps and projections.
mplfinance Candlesticks and volume.

All of them return Matplotlib figures you can still edit.

1 / 2

Two families

The most useful way to sort Python plotting libraries is by what they draw with.

Matplotlib-based libraries hand you a Figure and Axes, so everything you learned in this tutorial still works: labels, limits, ticks, annotations, styles, savefig. They produce static images (PNG, SVG, PDF), ideal for papers, reports and web pages that only need a picture.

Browser-based libraries produce JavaScript charts. They offer hover tooltips, zoom, pan and linked views, and they are the natural fit for dashboards and web apps. You customize them through their own APIs, and your Matplotlib knowledge applies only in concepts, not in code.

flowchart TD
  M["Matplotlib<br/>(Agg, SVG, PDF renderers)"] --> S["seaborn"]
  M --> P["plotnine"]
  M --> C["cartopy"]
  M --> F["mplfinance"]
  M --> D["pandas .plot()"]
  J["Browser JavaScript<br/>(plotly.js, BokehJS, Vega-Lite)"] --> PL["plotly"]
  J --> B["bokeh"]
  J --> A["altair"]

Left to right: the first group draws through Matplotlib, the second through browser JavaScript.

pandas plotting: the one you already have

Every pandas Series and DataFrame has a .plot accessor that calls Matplotlib for you. It is the shortest path from a table to a chart, and it returns a normal Axes, so you can polish the result with the methods from earlier lessons. The ax= argument lets you place it on a panel of your own figure.

Python pandas plotting returns Matplotlib objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first panel took one line from a DataFrame; the dashed mean line in the second came from plain Matplotlib. Both functions returned the very Axes object that we passed in, which is why the two worlds mix so well. For more, see Charts for analysis in pandas.

seaborn: statistics with good defaults

seaborn adds a high-level layer for statistical graphics. Instead of computing a group mean, a confidence interval or a kernel density yourself and then drawing it, you name the columns and let seaborn do both. It understands DataFrames, maps columns to color and size, and builds multi-panel layouts (FacetGrid, pairplot) in one call. Its figure-level functions create their own figures; its axes-level functions (scatterplot, boxplot, histplot) accept ax= like pandas does.

Python
import seaborn as sns

sns.set_theme(style="whitegrid")
ax = sns.boxplot(data=tips, x="day", y="total_bill", hue="smoker")   # axes-level
g = sns.relplot(data=tips, x="total_bill", y="tip", col="time", hue="day")  # figure-level
sns.pairplot(penguins, hue="species")

Everything seaborn returns is a Matplotlib artist, so ax.set_title(...) and g.fig.savefig(...) work. Choose seaborn when the question is statistical and the data lives in a tidy DataFrame. Use plain Matplotlib when you need exact control over every element, or the chart is not statistical.

plotnine: ggplot2 for Python

plotnine implements the grammar of graphics, the system behind R's ggplot2: you describe a chart as data, aesthetic mappings and layers added with +. It draws with Matplotlib, so it saves to the same formats and runs in the same places.

Python
from plotnine import ggplot, aes, geom_point, geom_smooth, facet_wrap, theme_minimal

chart = (
    ggplot(mpg, aes("displ", "hwy", color="class"))
    + geom_point()
    + geom_smooth(method="lm")
    + facet_wrap("drv")
    + theme_minimal()
)
chart.save("mileage.png", dpi=150)

It is a good choice if you already think in ggplot2 or like building charts by composing layers.

cartopy and mplfinance: specialists

cartopy adds map projections and geographic data to Matplotlib axes. You create axes with projection=ccrs.PlateCarree() (or another projection), then draw coastlines, borders and data in geographic coordinates. It needs map data files, which it downloads on first use, so it is typically used for weather, climate and geoscience figures.

Python
import cartopy.crs as ccrs

fig = plt.figure(figsize=(8, 4))
ax = plt.axes(projection=ccrs.Robinson())
ax.coastlines()
ax.set_global()
ax.scatter(lons, lats, transform=ccrs.PlateCarree())

mplfinance draws financial charts: candlesticks, OHLC bars, moving averages, volume panels and indicators from a DataFrame with Open, High, Low, Close, Volume columns and a date index.

Python
import mplfinance as mpf

mpf.plot(prices, type="candle", mav=(10, 20), volume=True, style="yahoo")

For geographic data frames, geopandas follows the pandas pattern (gdf.plot(column="population")) and also returns a Matplotlib Axes.

plotly, bokeh and altair: interactive charts

These three render in a browser and are the right tools when readers must hover, filter or zoom.

plotly (plotly.express for quick charts, plotly.graph_objects for control) makes interactive charts with tooltips, zoom and animations, and it powers the Dash dashboard framework. A figure exports to a standalone HTML file.

Python
import plotly.express as px

fig = px.scatter(df, x="gdp", y="life_exp", size="pop", color="continent",
                 hover_name="country", log_x=True)
fig.write_html("countries.html")

bokeh builds interactive plots and can run a Python server that reacts to widgets, which suits data apps and streaming data.

Python
from bokeh.plotting import figure, show

p = figure(title="Signal", tools="pan,wheel_zoom,hover")
p.line(x, y, line_width=2)
show(p)

altair is declarative: you describe the data encodings (x, y, color) and Vega-Lite does the rest. It is concise for exploratory work, but limited to data sizes that a browser can handle (5,000 rows by default).

Python
import altair as alt

alt.Chart(df).mark_circle().encode(
    x="gdp", y="life_exp", color="continent", tooltip="country"
).interactive()

Choosing between them

There is no single winner. Ask three questions.

  1. Where will the chart live? A paper, slide or PDF needs a static, precisely styled image: Matplotlib (or a library on top of it). A web page or dashboard that readers explore needs an interactive library.
  2. What are you drawing? Statistical comparisons in a tidy DataFrame: seaborn or plotnine. Maps: cartopy or geopandas. Finance: mplfinance. Free-form figures, diagrams or unusual layouts: Matplotlib.
  3. How much control do you need? The more custom the picture (exact positions, annotations, composites like the dashboard lesson or infographic project), the more you want the lower-level API.
Python What a wrapper library saves you

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The helper wraps about fifteen lines of Matplotlib behind one call, and the result is still an ordinary Axes that accepts a new title. That is exactly the relationship between Matplotlib and its neighbors: seaborn, plotnine and the others are carefully designed helpers like this one. When they do not do what you want, drop down to the Axes and finish the job yourself.

When Matplotlib is the right foundation

Matplotlib is the right choice when you need any of the following:

  • Publication-quality static output with exact control over size, fonts and vector formats.
  • Unusual charts and composites that no high-level library offers: custom layouts, annotations, diagrams, 3D, polar and image-like plots.
  • A stable, long-lived dependency: it has been maintained for over twenty years, runs everywhere (including servers without a display), and is the layer most other libraries assume.
  • Teaching and debugging: when you understand Figures, Axes and Artists, every library built on top becomes easier to use and fix.

It is a weaker choice for interactive dashboards with many linked views, huge datasets in the browser, or streaming data; there plotly, bokeh or a dedicated visualization stack fits better. Many projects use both: Matplotlib for the report, plotly for the web page.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these libraries draws its charts through Matplotlib?

    seaborn is built on Matplotlib and returns Matplotlib artists. plotly, bokeh and altair render in the browser with their own JavaScript engines.
  2. 2. What does df.plot.bar(ax=axes[0]) return?

    pandas plotting is a thin layer over Matplotlib and returns an Axes, so you can set titles, add lines or save the figure with the usual methods.
  3. 3. You need a hover-and-zoom chart inside a web dashboard. Which is the most natural choice?

    Interactive browser features come from JavaScript-based libraries. Matplotlib on the Agg backend produces static images.
  4. 4. A seaborn plot almost looks right but needs a custom annotation. What do you do?

    seaborn's axes-level functions return Matplotlib Axes objects, so every Matplotlib method is available for finishing touches.
  5. 5. Which library implements the grammar of graphics with layers added using +?

    plotnine ports R's ggplot2 to Python and draws with Matplotlib. cartopy is for maps, mplfinance for financial charts and bokeh for interactive plots.

Summary

  • Matplotlib is the foundation: seaborn, plotnine, cartopy, mplfinance, geopandas and pandas plotting all draw through it and hand back Matplotlib objects.
  • plotly, bokeh and altair draw in the browser with JavaScript; they excel at interactivity and dashboards but have their own APIs.
  • Use pandas .plot for a quick look, seaborn or plotnine for statistical charts from tidy data, cartopy for maps and mplfinance for markets.
  • Pick the tool by destination (static or interactive), subject (statistics, maps, finance, custom) and the control you need.
  • When a helper library falls short, finish the chart with plain Matplotlib on the returned Axes.

Next, put everything together in a first project: Project: Sales Dashboard.