1. Positioning of the three libraries
| Contrast | Matplotlib | Seaborn | Plotly |
|---|---|---|---|
| Positioning | General drawing base library | Statistical visualization | interactive visualization |
| Main features | Strong control ability | Simple code and rich statistical functions | Hover, Zoom, interaction |
| Pandas integrated | support | very tight | very tight |
| static chart | Strong | Strong | support |
| Interactive charts | Limited, depends on backend | Main inheritance Matplotlib | core competencies |
| Typical uses | Scientific research charts and detailed layouts | EDA, distribution and relationship analysis | Dashboard, Web charts |
Common imports:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
import plotly.graph_objects as go
Example data:
rng = np.random.default_rng(42)
df = pd.DataFrame({
"group": np.repeat(["A", "B", "C"], 100),
"x": rng.normal(size=300),
"y": rng.normal(size=300),
"value": rng.normal(loc=50, scale=10, size=300),
})
2. How to choose a chart
Different charts are suitable for answering different questions.
| Analysis purpose | Recommended chart |
|---|---|
| Time trend | Line Plot |
| Comparison between categories | Bar Plot |
| Univariate distribution | Histogram、KDE |
| Distribution differences and outliers | Box Plot、Violin Plot |
| relationship between two continuous variables | Scatter Plot |
| multivariate correlation | Heatmap |
| Multiple sets of variable relationships | Pair Plot |
| Cumulative amount and composition changes | Stacked Bar / Area |
| spatial distribution | Scatter Map / Geographic Map |
You should not only choose based on whether the chart is beautiful or not. You should first determine the data relationship you want to express.
For example, to correlate two continuous variables, Scatter Plot is usually more appropriate than Line Plot.
3. Matplotlib: Figure and Axes
The most important concepts of Matplotlib are Figure and Axes.
Figure
└── Axes
├── X / Y Axis
├── Title
├── Lines / Bars / Markers
├── Legend
└── Grid
- Figure: The entire canvas.
- Axes: A drawing area in the canvas that contains coordinate axes and graphic elements.
- Axis: specific X, Y coordinate axes and scales.
It is recommended to use object-oriented API:
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot([1, 2, 3, 4], [10, 15, 13, 20])
ax.set(
title="Sales Trend",
xlabel="Month",
ylabel="Sales",
)
ax.grid(alpha=0.3)
plt.show()
Compared with using plt.plot() directly, fig, ax = plt.subplots() is more suitable for building multiple subgraphs and reusable drawing functions.
Common drawing functions
ax.plot(x, y) # Line chart
ax.scatter(x, y) # Scatter plot
ax.bar(x, y) # bar chart
ax.barh(x, y) # horizontal bar chart
ax.hist(data) # Histogram
ax.boxplot(data) # boxplot
ax.imshow(matrix) # matrix/image
Styles and annotations
fig, ax = plt.subplots()
ax.plot(
[1, 2, 3],
[10, 15, 13],
label="Product A",
color="steelblue",
linestyle="--",
marker="o",
linewidth=2,
)
ax.set_title("Sales")
ax.set_xlabel("Month")
ax.set_ylabel("Revenue")
ax.legend()
ax.grid(alpha=0.3)
Common properties:
color: color.linestyle: Line type.linewidth: line width.marker: Data point markers.alpha: Transparency.label: legend name.
Subplots: multiple subgraphs
fig, axes = plt.subplots(
nrows=1,
ncols=2,
figsize=(10, 4),
layout="constrained",
)
axes[0].plot([1, 2, 3], [2, 4, 3])
axes[0].set_title("Line")
axes[1].bar(["A", "B", "C"], [10, 20, 15])
axes[1].set_title("Bar")
plt.show()
layout="constrained" can help automatically adjust the space of subfigures and labels.
save image
fig.savefig(
"chart.png",
dpi=300,
bbox_inches="tight",
)
fig.savefig(
"chart.svg",
bbox_inches="tight",
)
- PNG: Suitable for ordinary pictures and documents.
- SVG: Suitable for vector graphics and web pages.
- PDF: Suitable for reports and papers.
For static charts, Matplotlib is usually preferred.
4. Seaborn: Statistical visualization
Seaborn is built on Matplotlib, with the main advantage being the ability to use Pandas DataFrame directly and automatically handle categorical variables, color mapping and some statistical calculations.
sns.set_theme(style="whitegrid")
Scatter Plot
sns.scatterplot(
data=df,
x="x",
y="y",
hue="group",
)
plt.show()
Semantic Mapping
Seaborn can map data columns to different visual attributes:
| parameters | function |
|---|---|
x / y | coordinate position |
hue | color grouping |
style | mark or line style |
size | Point size or line width |
sns.scatterplot(
data=df,
x="x",
y="y",
hue="group",
style="group",
)
This mechanism is suitable for exploring relationships between multiple variables.
5. Data distribution visualization
When analyzing data, the distribution is usually more interesting than the mean.
Histogram
sns.histplot(
data=df,
x="value",
bins=25,
)
Displays the frequency distribution of values.
KDE:Kernel Density Estimation
sns.kdeplot(
data=df,
x="value",
hue="group",
fill=True,
)
KDE Constructs a smooth probability density curve using kernel density estimation.
It is not the actual frequency, and the degree of smoothing also affects the interpretation of the data.
Box Plot
sns.boxplot(
data=df,
x="group",
y="value",
)
Box Plot usually displays:
- median.
- first and third quartiles.
- Interquartile range (IQR).
- Whiskers。
- Data points beyond Whisker.
Whisker are not necessarily the maximum and minimum values of the sample, depending on the plotting rules.
Violin Plot
sns.violinplot(
data=df,
x="group",
y="value",
)
Violin Plot combines information about boxplots with the shape of the density distribution and is suitable for comparing the distributions of multiple groups.
| chart | Advantages |
|---|---|
| Histogram | Direct observation of frequency |
| KDE | Smooth observation distribution shape |
| Box Plot | Compare medians, dispersion, and outliers |
| Violin Plot | Compare distribution shapes between groups |
6. Category comparison and statistical relationships
Bar Plot
sns.barplot(
data=df,
x="group",
y="value",
estimator="mean",
errorbar="sd",
)
There is an important difference here:
- Matplotlib
ax.bar(): Draw the incoming height directly. - Seaborn
sns.barplot(): By default, statistical aggregation of data for each category will be performed.
barplot() of Seaborn uses the mean as the estimator by default and displays confidence intervals by default.
If you need to display the number of samples in each group, you can aggregate first and then draw:
counts = df["group"].value_counts()
sns.barplot(
x=counts.index,
y=counts.values,
)
Also available:
sns.countplot(
data=df,
x="group",
)
Regression Plot
sns.regplot(
data=df,
x="x",
y="y",
)
Suitable for quickly exploring linear trends and variable relationships.
However, visual fitting of regplot() should not be a direct substitute for formal statistical modeling and model diagnostics.
7. Heatmap and Pairplot
Heatmap
Often used to display correlation coefficient matrices:
corr = df[["x", "y", "value"]].corr()
sns.heatmap(
corr,
annot=True,
cmap="coolwarm",
vmin=-1,
vmax=1,
center=0,
)
Parameters:
annot=True: Display numerical value.cmap: color mapping.vmin/vmax: Fixed color range.center: Set the color center value.
Pairplot
sns.pairplot(
data=df,
vars=["x", "y", "value"],
hue="group",
)
Pairplot can quickly display the relationship between multiple numerical variables, as well as the distribution of each variable itself.
Suitable for EDA (Exploratory Data Analysis), but will produce a large number of subgraphs when the number of variables is too large.
8. Seaborn’s Axes-level and Figure-level
This is a more important design difference for Seaborn.
Axes-level Functions
Draw on the specified Matplotlib Axes:
fig, ax = plt.subplots()
sns.histplot(
data=df,
x="value",
ax=ax,
)
ax.set_title("Distribution")
Common functions:
scatterplot
lineplot
histplot
kdeplot
boxplot
violinplot
barplot
heatmap
Figure-level Functions
Directly manage the entire Figure and support faceted layout:
g = sns.relplot(
data=df,
x="x",
y="y",
col="group",
kind="scatter",
)
Mainly include:
| Figure-level | Main purpose |
|---|---|
relplot() | Scatter / Line |
displot() | Histogram / KDE / ECDF |
catplot() | Classification chart |
lmplot() | regression relationship |
The Figure-level function usually creates its own Figure and cannot simply pass in an existing ax like the Axes-level function.
For daily simple charts, use Axes-level first; use Figure-level when Faceting is required.
9. Plotly: Interactive visualization
Plotly is mainly used to generate interactive charts and supports:
- Hover Tooltip。
- Zoom / Pan。
- Legend Interaction。
- Chart zoom and export.
- Interactive 3D / Map.
- HTML output.
Plotly has two common interfaces:
- Plotly Express (
px): High-level interface suitable for most common charts. - Graph Objects (
go): Low-level interface, providing finer control.
The chart created by Plotly Express is itself graph_objects.Figure, so it can be modified after creation.
Plotly Express
fig = px.scatter(
df,
x="x",
y="y",
color="group",
hover_data=["value"],
title="Interactive Scatter Plot",
)
fig.show()
Common drawing functions:
px.line(...)
px.scatter(...)
px.bar(...)
px.histogram(...)
px.box(...)
px.violin(...)
px.imshow(...)
px.scatter_matrix(...)
Interactive line chart
trend = pd.DataFrame({
"date": pd.date_range("2026-01-01", periods=12, freq="MS"),
"sales": [10, 15, 13, 18, 22, 21, 25, 30, 28, 35, 40, 45],
})
fig = px.line(
trend,
x="date",
y="sales",
markers=True,
title="Monthly Sales",
)
fig.show()
Plotly provides interactive capabilities such as Hover and scaling by default, and there is no need to manually write JavaScript.
10. Plotly Graph Objects
Graph Objects can be used when different types of Trace, complex layouts, or a high degree of customization are required.
Figure / Trace / Layout
Figure
├── Data
│ ├── Scatter Trace
│ └── Bar Trace
└── Layout
├── Title
├── Axes
├── Legend
└── Annotations
Example:
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=[1, 2, 3],
y=[10, 15, 20],
mode="lines+markers",
name="Product A",
)
)
fig.add_trace(
go.Scatter(
x=[1, 2, 3],
y=[8, 12, 18],
mode="lines+markers",
name="Product B",
)
)
fig.update_layout(
title="Sales Comparison",
xaxis_title="Month",
yaxis_title="Sales",
)
fig.show()
Update existing chart
Figure created by Plotly Express can also be modified:
fig = px.scatter(df, x="x", y="y")
fig.update_traces(marker_size=8)
fig.update_layout(
title="Scatter Plot",
template="plotly_white",
)
fig.update_xaxes(title="X Value")
fig.update_yaxes(title="Y Value")
Subplots
from plotly.subplots import make_subplots
fig = make_subplots(
rows=1,
cols=2,
subplot_titles=["Line", "Bar"],
)
fig.add_trace(
go.Scatter(x=[1, 2, 3], y=[2, 4, 3]),
row=1,
col=1,
)
fig.add_trace(
go.Bar(x=["A", "B"], y=[10, 20]),
row=1,
col=2,
)
fig.show()
When you need a simple interactive chart, use Plotly Express first; only turn to Graph Objects when you need fine control.
11. Hover, Facet and export of Plotly
Custom Hover
fig = px.scatter(
df,
x="x",
y="y",
color="group",
hover_data=["value"],
hover_name="group",
)
Facet
fig = px.scatter(
df,
x="x",
y="y",
facet_col="group",
)
It is equivalent to splitting it into multiple subgraphs according to categorical variables.
HTML output
fig.write_html("chart.html")
Interactive HTML charts can be generated.
static pictures
fig.write_image("chart.png")
fig.write_image("chart.svg")
Exporting static images usually requires the installation and configuration of dependencies such as Kaleido; the current version may also require Chrome/Chromium.
12. Important principles of data visualization
Correct choice of axis range
Histograms are often suitable for starting from scratch to avoid exaggerating class differences.
For line charts, the vertical axis range can be reasonably set based on the analysis goals, but the scale needs to be clearly displayed.
Pay attention to data aggregation
For example, when using sns.barplot(), the group means may be plotted instead of the original data.
It should be clear:
Count
Mean
Median
Sum
Percentage
Different aggregation methods have completely different meanings.
Avoid Overplotting
If there are hundreds of thousands of scatter points:
ax.scatter(x, y, alpha=0.1, s=3)
Overlap can be mitigated through transparency and point size.
Also consider:
- Hexbin。
- 2D Histogram。
- Data sampling.
- Density Plot。
A large number of interactive data points can cause browser rendering stress. Plotly can use WebGL Trace in applicable scenarios, but it does not mean that unlimited data amounts can be rendered smoothly.
color map
Common types:
| Type | scene |
|---|---|
| Sequential | Values from low to high |
| Diverging | A meaningful center point, such as the zero point of the correlation coefficient |
| Categorical | Different categories, no order of size |
Try to choose a color scheme that is legible and suitable for users with different color vision.
Annotation and reproducibility
The chart should contain:
- Clear title.
- Axis name.
- unit.
- Necessary legend.
- Data source (in formal report).
- Clear statistical caliber.
For analytical reports, filter conditions and aggregation logic should be fixed so that charts can be regenerated from the raw data.
13. How to choose among the three
| Usage scenarios | Recommended |
|---|---|
| Simple line chart, scatter chart | Matplotlib |
| Papers, static reports | Matplotlib |
| DataFrame EDA | Seaborn |
| Data distribution, group comparison | Seaborn |
| Correlation coefficient matrix | Seaborn |
| Notebook interactive exploration | Plotly |
| HTML interactive chart | Plotly |
| Python Dashboard | Plotly + Dash / Streamlit |
| Fine multi-subgraph layout | Matplotlib / Plotly Graph Objects |
Recommended usage combinations
Pandas
↓
Data Cleaning / Aggregation
↓
Visualization
├── Matplotlib → Static Plot
├── Seaborn → Statistical Plot
└── Plotly → Interactive Plot
In fact, there is no need for all charts to be implemented separately using three libraries.
Common workflow:
- Pandas is responsible for cleaning and aggregation.
- Seaborn Quickly explore data distribution and correlations.
- Matplotlib Adjust static chart style.
- Plotly Make the final chart that requires interaction.
Summary
| Knowledge points | importance |
|---|---|
| Matplotlib Figure / Axes | core |
plt.subplots() | core |
| Line / Scatter / Bar / Histogram | core |
| Matplotlib style, label, save | high frequency |
Seaborn hue / style / size | core |
Seaborn histplot / boxplot / kdeplot | core |
Seaborn heatmap / pairplot | high frequency |
| Axes-level / Figure-level | important |
| Plotly Express | core |
| Plotly Graph Objects | important |
| Hover / Facet / HTML Export | high frequency |
| Chart selection and statistical caliber | core |
The three most important concepts:
- Figure/Axes model ofMatplotlib: Master the relationship between canvas, subgraphs, and graphic elements.
- Statistical VisualizationofSeaborn: Quickly explore variable relationships and data distribution using DataFrame and semantic mapping.
- Plotly's Figure/Trace/Layout model: Create interactive charts with declarative data structures.
For daily data analysis, familiarity with Matplotlib and Seaborn can complete most static visualization work; when Hover, Zoom, dynamic filtering or HTML interactive display is required, use Plotly.