Matplotlib vs Plotly: Which Python Chart Tool Should You Choose?

Matplotlib vs Plotly: Which Python Chart Tool Should You Choose?

Matplotlib 对比 Plotly:你应该选择哪种 Python 图表工具?

Data Visualization Matplotlib vs Plotly: Which Python Chart Tool Should You Choose? From static plots to interactive data exploration. 数据可视化 Matplotlib 对比 Plotly:你应该选择哪种 Python 图表工具?从静态绘图到交互式数据探索。

If you are a data scientist or analyst, a significant part of your workload will be creating data visualisations, and if you are a Python user, you’re likely already familiar with or have a passing knowledge of Matplotlib. It’s a cornerstone of Python plotting. 如果你是一名数据科学家或分析师,工作中的很大一部分内容就是创建数据可视化。如果你是 Python 用户,你可能已经熟悉或了解 Matplotlib。它是 Python 绘图的基石。

But, as is often the case, what if you want your audience (or yourself) to interact with your plots – zoom in on details, hover over points to see values, or toggle datasets on and off? For that, the Plotly charting library offers a compelling, modern alternative. It often requires only minimal changes to your existing codebase to significantly improve the user experience. 但通常情况下,如果你希望你的受众(或你自己)能够与图表进行交互——比如放大细节、悬停在数据点上查看数值,或者切换数据集的显示与隐藏——该怎么办呢?为此,Plotly 绘图库提供了一个引人注目的现代替代方案。它通常只需对现有代码库进行极小的改动,就能显著提升用户体验。

In this article, I’ll provide several examples of using Plotly and Matplotlib on the same datasets to illustrate their key differences. By the end, you should have enough knowledge to decide exactly why you might want to start using one over the other. I have no affiliation or commercial association with the Plotly or Matplotlib libraries or the people or companies who created them. 在本文中,我将提供几个在相同数据集上使用 Plotly 和 Matplotlib 的示例,以说明它们的主要区别。读完本文,你应该有足够的知识来决定为什么要在两者之间做出选择。我与 Plotly 或 Matplotlib 库,以及创建它们的个人或公司没有任何隶属或商业关联。

What is Matplotlib?

什么是 Matplotlib?

If you’ve done any graphing with Python in the past, you likely already know Matplotlib. It’s the veteran plotting library for Python, providing tremendous flexibility and control for creating static, publication-quality charts and graphs. Developed by John D. Hunter, an American neurobiologist, it was initially designed to mimic MATLAB’s plotting capabilities. Its strength lies in its ubiquity, extensive documentation, and fine-grained control over almost every plot element. Another popular library, Seaborn, is built on Matplotlib and provides higher-level interfaces for drawing attractive statistical graphics. The primary output is typically static images, such as PNG, JPG, and PDF. 如果你过去使用 Python 进行过绘图,你可能已经了解 Matplotlib。它是 Python 的老牌绘图库,为创建静态、出版级的图表提供了极大的灵活性和控制力。它由美国神经生物学家 John D. Hunter 开发,最初旨在模仿 MATLAB 的绘图功能。它的优势在于其普及性、详尽的文档以及对几乎每个图表元素的精细控制。另一个流行的库 Seaborn 是基于 Matplotlib 构建的,提供了用于绘制美观统计图形的高级接口。其主要输出通常是静态图像,如 PNG、JPG 和 PDF。

What is Plotly, and why do you need it?

什么是 Plotly,为什么你需要它?

Plotly is a modern, open-source graphing library that creates interactive visualisations. Developed by Plotly Technologies, it allows you to build beautiful charts that users can interact with directly in a web browser or a Jupyter notebook. These interactions include zooming, panning, hovering to see data point values, selecting regions, and more. Plotly charts are described as JSON objects and rendered using the Plotly.js JavaScript library. The Python library (plotly.py) provides an easy interface for creating these JSON structures. Plotly 是一个现代化的开源绘图库,用于创建交互式可视化。它由 Plotly Technologies 开发,允许你构建美观的图表,用户可以直接在 Web 浏览器或 Jupyter Notebook 中与之交互。这些交互包括缩放、平移、悬停查看数据点数值、选择区域等。Plotly 图表被描述为 JSON 对象,并使用 Plotly.js JavaScript 库进行渲染。Python 库 (plotly.py) 提供了一个简单的接口来创建这些 JSON 结构。

Why do you need it? Mainly because its interactivity transforms data visualisation from a passive viewing experience into an active exploration tool. It allows users to: 为什么你需要它?主要是因为它的交互性将数据可视化从被动的观看体验转变为主动的探索工具。它允许用户:

  • Explore Details. Zoom into dense areas of a plot.
  • 探索细节。 放大图表的密集区域。
  • Identify Specific Points. Hover over elements to see exact values without cluttering the plot with labels.
  • 识别特定点。 悬停在元素上查看精确数值,而无需用标签填满图表。
  • Compare Subsets. Toggle traces (lines, bars, etc.) on and off via the legend.
  • 比较子集。 通过图例切换轨迹(线条、柱状图等)的显示与隐藏。
  • Share Richer Insights. Embed fully interactive plots in websites, dashboards (like Plotly Dash), or share them as standalone HTML files.
  • 分享更丰富的见解。 将完全交互式的图表嵌入网站、仪表板(如 Plotly Dash),或将其作为独立的 HTML 文件共享。

Generally, interactive plots are often far more insightful than static images for exploratory data analysis, presentations, and web applications. 通常,对于探索性数据分析、演示文稿和 Web 应用程序而言,交互式图表往往比静态图像具有更深刻的洞察力。

Ok, with that being said, let’s get into our examples. 好了,话不多说,让我们进入示例环节。

Prerequisites

前置要求

You’ll need Python and pip (or Conda) installed. We’ll use Pandas for basic data handling, Matplotlib and Seaborn for the baseline comparison, and Plotly for the interactive alternative. Before that, let’s set up our development environment. I use Conda for this, but you can use whatever tool or method suits you. 你需要安装 Python 和 pip(或 Conda)。我们将使用 Pandas 进行基本数据处理,使用 Matplotlib 和 Seaborn 进行基准对比,并使用 Plotly 作为交互式替代方案。在此之前,让我们设置开发环境。我使用 Conda,但你可以使用任何适合你的工具或方法。

#create our test environment (base)
$ conda create -n python_plots python=3.13 -y

Now, activate the environment and install the required libraries. 现在,激活环境并安装所需的库。

(base) $ conda activate python_plots
(python_plots) $ pip install matplotlib seaborn pandas plotly jupyter numpy

Now type in jupyter notebook into your command line prompt. You should see a Jupyter Notebook open in your browser. If that doesn’t happen automatically, you’ll likely see a screenful of information after the jupyter notebook command. Near the bottom, you will find a URL to copy and paste into your browser to launch the Jupyter Notebook. 现在在命令行提示符中输入 jupyter notebook。你应该会看到 Jupyter Notebook 在浏览器中打开。如果它没有自动打开,你在输入命令后可能会看到满屏的信息。在底部附近,你会找到一个 URL,将其复制并粘贴到浏览器中即可启动 Jupyter Notebook。

Example 1: A Simple Scatter Plot

示例 1:简单的散点图

Let’s start with a basic scatter plot comparing two variables. First, we’ll generate some sample data using NumPy and Pandas. 让我们从一个比较两个变量的基本散点图开始。首先,我们将使用 NumPy 和 Pandas 生成一些样本数据。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
from timeit import default_timer as timer

# Generate some sample data
np.random.seed(42)
n_points = 100
data = pd.DataFrame({
    'x_values': np.random.rand(n_points) * 10,
    'y_values': 2.5 * np.random.rand(n_points) * 10 + np.random.randn(n_points) * 5,
    'category': np.random.choice(['A', 'B', 'C'], n_points)
})

print(data.head())

Now, we can plot this using Matplotlib (via Seaborn for slightly nicer defaults and easy colouring by category). 现在,我们可以使用 Matplotlib(通过 Seaborn 以获得更好的默认设置和轻松的分类着色)来绘制它。

# --- Matplotlib/Seaborn ---
start = timer()
plt.figure(figsize=(8, 5))
sns.scatterplot(data=data, x='x_values', y='y_values', hue='category')
plt.title('Matplotlib Scatter Plot')
plt.xlabel('X Values')
plt.ylabel('Y Values')
plt.grid(True)
plt.show()
print(f"Matplotlib time: {timer()-start:.4f} seconds")

This generates a familiar static scatter plot. Now, let’s create the same plot using Plotly Express, which provides a high-level interface similar to Seaborn. Unfortunately, I can only post an image of the chart that’s produced. To experience the full range of interactivity that Plotly provides, please run the code in your own environment. 这会生成一个熟悉的静态散点图。现在,让我们使用 Plotly Express 创建相同的图表,它提供了类似于 Seaborn 的高级接口。遗憾的是,我只能发布生成的图表图片。要体验 Plotly 提供的全部交互功能,请在你自己的环境中运行代码。

import plotly.express as px
# --- Plotly Express ---
start = timer()
fig = px.scatter(data, x='x_values', y='y_values', color='category')