首页 > 教程 > 使用Python的matplotlib库绘制图表

使用Python的matplotlib库绘制图表

时间:2024-04-25 | 来源: | 阅读:122

话题: T 画图 Python

本文将介绍如何使用 Python 的 matplotlib 库画图,记录一些常用的画图 demo 代码

本文将介绍如何使用Python的matplotlib库绘制图表,并记录一些常用的绘图示例代码。

安装matplotlib库:

# 建议先切换到虚拟环境中
pip install matplotlib

中文显示设置:

新版的matplotlib已经支持字体回退功能,因此可以直接设置字体为Times New Roman和SimSun(宋体),以实现英文以Times New Roman显示,中文以宋体显示。

import matplotlib.pyplot as plt

plt.rcParams['font.family'] = ['Times New Roman','SimSun']

折线图和点线图:

使用plot函数可以绘制折线图和点线图,通过marker参数设置点的样式,markersize参数设置点的大小。

import matplotlib.pyplot as plt

# 设置中文字体为Times New Roman和宋体
plt.rcParams['font.family'] = ['Times New Roman','SimSun']

# 生成数据
x = range(0, 6)
y = [i**3 for i in x]

# 绘制点线图
plt.plot(x, y, marker='o', markersize=6, label='y=x^3')

# 添加坐标轴标签
plt.xlabel('x')
plt.ylabel('y')

# 配置坐标轴范围
plt.xlim(0)
plt.ylim(0)

# 添加图例
plt.legend()

# 配置紧凑布局
plt.tight_layout(pad=0.1)

# 保存图片
plt.savefig('plot.png')

柱状图和堆积柱状图:

使用bar函数绘制柱状图,通过bottom参数可以绘制堆积柱状图。

# 生成数据
x = range(1, 6)
y1 = [1 for i in x]
y2 = [i for i in x]

# 绘制堆积柱状图
plt.bar(x, y1, color='tab:blue', edgecolor='black', label='y1=1', width=0.5)
plt.bar(x, y2, bottom=y1, color='tab:orange', edgecolor='black', label='y2=x', width=0.5)

坐标轴断点:

有时需要在柱状图中添加y轴的断点,可以通过画两个相同的图,并配置不同的y轴范围,然后在两个图之间添加截断线的方式来实现。

# 生成数据
x = range(1, 5)
y = [i**3 for i in x]

# 分别绘制上下两个图
b1 = ax1.bar(x, y, color='tab:blue', edgecolor='black', label='y1=1', width=0.5)
b2 = ax2.bar(x, y, color='tab:blue', edgecolor='black', label='y1=1', width=0.5)

# 显示数据
ax1.bar_label(b1, fmt='%d', label_type='edge')
ax2.bar_label(b2, fmt='%d', label_type='edge')

# 配置上图的坐标轴范围
ax1.set_ylim(15)
ax1.set_yticks([20, 40, 60])
# 删掉上图的下边框
ax1.spines['bottom'].set_visible(False)
# 隐藏上图的x轴
ax1.xaxis.set_visible(False)

# 配置下图的坐标轴范围
ax2.set_ylim(0, 9)
ax2.set_yticks([0, 2, 4, 6, 8])
# 删掉下图的上边框
ax2.spines['top'].set_visible(False)

# 添加截断线,由于图高度比例为1:2,所以截断线的y坐标也需要按比例设置
d = .015
kwargs = dict(transform=ax1.transAxes, color='k', clip_on=False)
ax1.plot((-d, +d), (-2*d, +2*d), **kwargs) 
ax1.plot((1 - d, 1 + d), (-2*d, +2*d), **kwargs)

kwargs.update(transform=ax2.transAxes)
ax2.plot((-d, +d), (1 - d, 1 + d), **kwargs)
ax2.plot((1 - d, 1 + d), (1 - d, 1 + d), **kwargs)

参考资料:

  • 【GitHub】Implement Font-Fallback in Matplotlib
  • 【matplotlib】axes.Axes.bar_label
  • 【matplotlib】Broken Axis

本文作者: ywang_wnlo
本文链接: https://ywang-wnlo.github.io/posts/731b80f7/
版权声明: 本博客所有文章除特别声明外,均采用BY-NC-SA许可协议。转载请注明


湘ICP备2022002427号-10湘公网安备:43070202000427号
© 2013~2019 haote.com 好特网