Matplotlib绘图:折线图、柱状图、散点图等一网打尽 – wiki基地

Matplotlib 绘图:折线图、柱状图、散点图等一网打尽

Matplotlib 是 Python 中最流行的 2D 绘图库,它提供了丰富的绘图功能,可以帮助数据科学家和工程师以可视化方式探索数据、展示结果。本文将深入探讨 Matplotlib 的核心绘图类型,包括折线图、柱状图、散点图、直方图、饼图等,并结合实例详细讲解其用法。

1. Matplotlib 基础

1.1 安装与导入

Matplotlib 通常与 NumPy 一起使用,因此在安装 Matplotlib 之前,请确保已安装 NumPy。可以使用 pip 安装 Matplotlib:

bash
pip install matplotlib

在 Python 代码中,通常使用以下方式导入 Matplotlib 的 pyplot 模块:

python
import matplotlib.pyplot as plt
import numpy as np

pyplot 模块提供了一个类似于 MATLAB 的绘图接口,使得绘图过程更加直观。

1.2 Figure 和 Axes

在 Matplotlib 中,Figure 对象代表整个绘图窗口,而 Axes 对象代表 Figure 中的一个绘图区域。一个 Figure 可以包含多个 Axes,每个 Axes 都有自己的坐标系,可以在其中绘制不同类型的图表。

创建 FigureAxes 的基本方法如下:

python
fig, ax = plt.subplots() # 创建一个 Figure 和一个 Axes

也可以使用 plt.figure() 创建 Figure,然后使用 add_subplot() 方法添加 Axes

python
fig = plt.figure()
ax1 = fig.add_subplot(2, 1, 1) # 创建一个 2x1 的网格,在第一个位置添加 Axes
ax2 = fig.add_subplot(2, 1, 2) # 在第二个位置添加 Axes

1.3 基本绘图流程

Matplotlib 的基本绘图流程通常包括以下几个步骤:

  1. 准备数据: 使用 NumPy 或其他数据结构准备要绘制的数据。
  2. 创建 Figure 和 Axes: 使用 plt.subplots()plt.figure() 创建 FigureAxes
  3. 绘制图表: 使用 Axes 对象的绘图方法(如 plot(), bar(), scatter() 等)绘制图表。
  4. 自定义图表: 添加标题、标签、图例、网格线等,调整颜色、线型、标记等,使图表更具可读性和美观性。
  5. 显示或保存图表: 使用 plt.show() 显示图表,或使用 plt.savefig() 将图表保存为文件。

2. 常见图表类型

2.1 折线图 (Line Plot)

折线图用于显示数据随时间或其他连续变量的变化趋势。Axes.plot() 方法用于绘制折线图。

示例:

“`python

准备数据

x = np.linspace(0, 10, 100)
y = np.sin(x)

创建 Figure 和 Axes

fig, ax = plt.subplots()

绘制折线图

ax.plot(x, y)

添加标题和标签

ax.set_title(‘Sine Wave’)
ax.set_xlabel(‘x’)
ax.set_ylabel(‘sin(x)’)

显示图表

plt.show()
“`
自定义折线图:

  • 颜色 (color): color='red'color='#FF0000' (十六进制颜色码)
  • 线型 (linestyle): linestyle='-' (实线), linestyle='--' (虚线), linestyle='-.' (点划线), linestyle=':' (点线)
  • 线宽 (linewidth): linewidth=2
  • 标记 (marker): marker='o' (圆圈), marker='*' (星号), marker='+' (加号), marker='x' (叉号)
  • 标记大小 (markersize): markersize=8
  • 图例 (legend): plt.legend()ax.legend()。在 plot() 中使用 label 参数设置图例标签。

“`python

准备数据

x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

创建 Figure 和 Axes

fig, ax = plt.subplots()

绘制折线图,并自定义样式

ax.plot(x, y1, color=’blue’, linestyle=’-‘, linewidth=2, marker=’o’, markersize=4, label=’sin(x)’)
ax.plot(x, y2, color=’red’, linestyle=’–‘, linewidth=1, marker=’x’, markersize=4, label=’cos(x)’)

添加标题和标签

ax.set_title(‘Sine and Cosine Waves’)
ax.set_xlabel(‘x’)
ax.set_ylabel(‘y’)

添加图例

ax.legend()

显示图表

plt.show()
“`

2.2 柱状图 (Bar Chart)

柱状图用于比较不同类别的数据大小。Axes.bar() 方法用于绘制柱状图。

示例:

“`python

准备数据

categories = [‘A’, ‘B’, ‘C’, ‘D’]
values = [25, 40, 15, 30]

创建 Figure 和 Axes

fig, ax = plt.subplots()

绘制柱状图

ax.bar(categories, values)

添加标题和标签

ax.set_title(‘Bar Chart Example’)
ax.set_xlabel(‘Categories’)
ax.set_ylabel(‘Values’)

显示图表

plt.show()
“`
自定义柱状图:

  • 颜色 (color): color=['red', 'green', 'blue', 'yellow'] (为每个柱子设置不同颜色)
  • 宽度 (width): width=0.5 (调整柱子的宽度)
  • 对齐方式 (align): align='center' (默认), align='edge'
  • 水平柱状图 (barh): 使用 ax.barh() 绘制水平柱状图。
  • 堆叠柱状图: 多次调用 bar(),并设置 bottom 参数。
  • 分组柱状图: 通过调整柱子的位置和宽度实现。

“`python

准备数据

categories = [‘A’, ‘B’, ‘C’, ‘D’]
values1 = [25, 40, 15, 30]
values2 = [15, 25, 30, 20]

创建 Figure 和 Axes

fig, ax = plt.subplots()

绘制分组柱状图

width = 0.35
x = np.arange(len(categories))

ax.bar(x – width/2, values1, width, label=’Group 1′, color=’blue’)
ax.bar(x + width/2, values2, width, label=’Group 2′, color=’red’)

添加标题和标签

ax.set_title(‘Grouped Bar Chart’)
ax.set_xlabel(‘Categories’)
ax.set_ylabel(‘Values’)
ax.set_xticks(x)
ax.set_xticklabels(categories)

添加图例

ax.legend()

显示图表

plt.show()
“`

“`python

准备数据

categories = [‘A’, ‘B’, ‘C’, ‘D’]
values1 = [25, 40, 15, 30]
values2 = [15, 25, 30, 20]

创建 Figure 和 Axes

fig, ax = plt.subplots()

绘制堆叠柱状图

ax.bar(categories, values1, label=’Group 1′, color=’blue’)
ax.bar(categories, values2, bottom=values1, label=’Group 2′, color=’red’)

添加标题和标签

ax.set_title(‘Stacked Bar Chart’)
ax.set_xlabel(‘Categories’)
ax.set_ylabel(‘Values’)

添加图例

ax.legend()

显示图表

plt.show()
“`

2.3 散点图 (Scatter Plot)

散点图用于显示两个变量之间的关系。Axes.scatter() 方法用于绘制散点图。

示例:

“`python

准备数据

x = np.random.rand(50)
y = np.random.rand(50)

创建 Figure 和 Axes

fig, ax = plt.subplots()

绘制散点图

ax.scatter(x, y)

添加标题和标签

ax.set_title(‘Scatter Plot Example’)
ax.set_xlabel(‘x’)
ax.set_ylabel(‘y’)

显示图表

plt.show()
“`

自定义散点图:

  • 颜色 (color): color='red'
  • 标记 (marker): marker='o' (圆圈), marker='*' (星号), marker='+' (加号)
  • 标记大小 (s): s=50 (使用数值) 或 s=sizes (使用数组,每个点可以有不同的大小)
  • 透明度 (alpha): alpha=0.5 (0 到 1 之间的值,0 表示完全透明,1 表示完全不透明)
  • 颜色映射 (cmap): 使用 cmapc 参数,可以根据第三个变量的值为每个点设置不同的颜色。

“`python

准备数据

x = np.random.rand(50)
y = np.random.rand(50)
sizes = np.random.rand(50) * 100 # 随机大小
colors = np.random.rand(50) # 随机颜色

创建 Figure 和 Axes

fig, ax = plt.subplots()

绘制散点图,自定义样式

scatter = ax.scatter(x, y, s=sizes, c=colors, cmap=’viridis’, alpha=0.7)

添加标题和标签

ax.set_title(‘Scatter Plot with Size and Color’)
ax.set_xlabel(‘x’)
ax.set_ylabel(‘y’)

添加颜色条

fig.colorbar(scatter)

显示图表

plt.show()
“`

2.4 直方图 (Histogram)

直方图用于显示数据分布的频率。Axes.hist() 方法用于绘制直方图。

示例:

“`python

准备数据

data = np.random.randn(1000) # 生成 1000 个标准正态分布的随机数

创建 Figure 和 Axes

fig, ax = plt.subplots()

绘制直方图

ax.hist(data, bins=30) # bins 参数指定直方图的柱子数量

添加标题和标签

ax.set_title(‘Histogram Example’)
ax.set_xlabel(‘Value’)
ax.set_ylabel(‘Frequency’)

显示图表

plt.show()
“`

自定义直方图:

  • 柱子数量 (bins): bins=10 (整数), bins=[0, 1, 2, 3] (自定义区间)
  • 颜色 (color): color='skyblue'
  • 边框颜色 (edgecolor): edgecolor='black'
  • 归一化 (density): density=True (将频率转换为概率密度)
  • 累积直方图 (cumulative): cumulative=True
  • 直方图类型 (histtype): histtype='bar' (默认), histtype='step' (阶梯状), histtype='stepfilled'

2.5 饼图 (Pie Chart)

饼图用于显示各部分占总体的比例。Axes.pie() 方法用于绘制饼图。

示例:

“`python

准备数据

labels = [‘A’, ‘B’, ‘C’, ‘D’]
sizes = [15, 30, 45, 10]

创建 Figure 和 Axes

fig, ax = plt.subplots()

绘制饼图

ax.pie(sizes, labels=labels, autopct=’%1.1f%%’, startangle=90)

添加标题

ax.set_title(‘Pie Chart Example’)

保证饼图是圆形

ax.axis(‘equal’)

显示图表

plt.show()
“`

自定义饼图:

  • 标签 (labels): labels=['A', 'B', 'C', 'D']
  • 百分比格式 (autopct): autopct='%1.1f%%' (保留一位小数), autopct='%1.0f%%' (不保留小数)
  • 起始角度 (startangle): startangle=90 (从 90 度开始)
  • 阴影 (shadow): shadow=True
  • 突出显示 (explode): explode=(0, 0.1, 0, 0) (将第二个扇区突出显示)
  • 颜色 (colors): colors=['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
  • 逆时针方向 (counterclock): counterclock=False

2.6 其他常用图表

除了上述几种常见的图表类型外,Matplotlib 还支持许多其他图表类型,例如:

  • 箱线图 (Box Plot): ax.boxplot()
  • 小提琴图 (Violin Plot): ax.violinplot()
  • 等高线图 (Contour Plot): ax.contour()ax.contourf()
  • 热力图 (Heatmap): ax.imshow()
  • 3D 图表: 使用 mpl_toolkits.mplot3d 模块中的 Axes3D 对象

3. 图表美化

Matplotlib 提供了丰富的选项来自定义图表的外观,使图表更具可读性和美观性。

3.1 标题、标签和图例

  • 标题 (Title): ax.set_title()
  • x 轴标签 (xlabel): ax.set_xlabel()
  • y 轴标签 (ylabel): ax.set_ylabel()
  • 图例 (Legend): ax.legend()plt.legend()。在绘图方法中使用 label 参数设置图例标签。

3.2 坐标轴范围和刻度

  • 坐标轴范围 (xlim, ylim): ax.set_xlim(), ax.set_ylim()
  • 刻度 (xticks, yticks): ax.set_xticks(), ax.set_yticks()
  • 刻度标签 (xticklabels, yticklabels): ax.set_xticklabels(), ax.set_yticklabels()

3.3 网格线

  • 显示网格线 (grid): ax.grid(True)
  • 自定义网格线: ax.grid(color='gray', linestyle='--', linewidth=0.5)

3.4 文本注释

  • 添加文本 (text): ax.text(x, y, 'text')
  • 添加箭头注释 (annotate): ax.annotate('text', xy=(x, y), xytext=(x_text, y_text), arrowprops=dict(facecolor='black', shrink=0.05))

3.5 样式表 (Style Sheets)

Matplotlib 提供了多种预定义的样式表,可以快速改变图表的整体外观。

“`python

使用样式表

plt.style.use(‘ggplot’) # 使用 ggplot 样式

查看所有可用的样式表

print(plt.style.available)
“`

3.6 多图布局

  • plt.subplots(): 最常用的方法,可以一次性创建多个子图,并返回一个包含 Figure 对象和 Axes 对象数组的元组。

    “`python
    fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(12, 6)) # 创建一个 2×3 的子图网格

    访问和绘制子图

    axes[0, 0].plot(x, y) # 在第一个子图 (第一行第一列) 上绘制
    axes[1, 2].scatter(x, z) # 在第三个子图(第二行第三列)上绘制
    “`

  • plt.subplot(): 一次创建一个子图,并将其设置为当前活动的 Axes

    “`python
    plt.figure(figsize=(8, 6))

    plt.subplot(2, 1, 1) # 创建一个 2×1 的网格,选择第一个子图
    plt.plot(x, y)
    plt.title(‘Subplot 1’)

    plt.subplot(2, 1, 2) # 选择第二个子图
    plt.plot(x, z)
    plt.title(‘Subplot 2’)

    plt.tight_layout() # 自动调整子图布局,防止重叠
    plt.show()
    ``
    * **
    plt.subplot2grid()`:** 更灵活的子图布局方式,允许子图跨越多行或多列。

    “`python
    plt.figure(figsize=(10, 8))

    ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=2) # 跨越两列
    ax2 = plt.subplot2grid((3, 3), (1, 0), rowspan=2) # 跨越两行
    ax3 = plt.subplot2grid((3, 3), (1, 1), colspan=2, rowspan=2)

    ax1.plot(x, y)
    ax2.scatter(x, z)
    ax3.hist(data)

    plt.tight_layout()
    plt.show()
    “`

  • gridspec: matplotlib.gridspec 模块提供了更高级的子图布局控制。

    “`python
    import matplotlib.gridspec as gridspec

    fig = plt.figure(figsize=(10, 8))
    gs = gridspec.GridSpec(3, 3) # 创建一个 3×3 的网格

    ax1 = plt.subplot(gs[0, :2]) # 第一行,跨越前两列
    ax2 = plt.subplot(gs[1:, 0]) # 第二行和第三行,第一列
    ax3 = plt.subplot(gs[1:, 1:]) # 第二行和第三行, 第二列和第三列

    ax1.plot(x,y)
    ax2.scatter(x,z)
    ax3.hist(data)

    plt.tight_layout()
    plt.show()
    “`

    4. 总结

Matplotlib 是一个功能强大且灵活的 Python 绘图库,可以创建各种类型的图表,并进行高度自定义。本文详细介绍了折线图、柱状图、散点图、直方图、饼图等常见图表类型的绘制方法,以及图表美化的技巧。掌握 Matplotlib 的基本用法,将有助于数据科学家和工程师更好地进行数据可视化和结果展示。

希望这篇文章对您有所帮助!如果您有任何其他问题,请随时提出。

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部