Featured image of post Python Basic 15 pyplot 常用绘图操作

Python Basic 15 pyplot 常用绘图操作

本篇文章主要介绍Python pyplot的常用绘图操作

pyplot 是 matplotlib 库中的一个模块,提供了类似 MATLAB 的绘图接口。这篇指南帮你快速掌握 pyplot 的常用方法!(≧▽≦)

基本设置

1
2
3
import matplotlib.pyplot as plt
# 下面这条命令可以让图形在Jupyter Notebook中直接显示哦~
%matplotlib inline

最简单的折线图 📈

1
2
3
plt.plot([1, 2, 3, 4])  # y值自动生成
plt.ylabel('纵轴标签')   # 添加纵轴标签
plt.show()              # 显示图形

完整版折线图 🖍️

1
2
3
4
5
6
7
8
9
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]

plt.plot(x, y, 'ro-')  # 'r'红色, 'o'圆点, '-'实线
plt.title('漂亮的折线图')   # 添加标题
plt.xlabel('x轴')        # 添加x轴标签
plt.ylabel('y轴')        # 添加y轴标签
plt.grid(True)          # 显示网格
plt.show()

同时绘制多个图形 🌈

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import numpy as np

# 生成0到5之间均匀分布的100个数
t = np.linspace(0, 5, 100)

plt.plot(t, t, 'r--',  label='线性')    # 红色虚线
plt.plot(t, t**2, 'bs-', label='平方')  # 蓝色方块实线
plt.plot(t, t**3, 'g^:', label='立方')  # 绿色三角点线

plt.legend()  # 显示图例
plt.show()

散点图绘制 ✨

1
2
3
4
5
6
7
8
x = np.random.randn(100)  # 100个随机数
y = np.random.randn(100)
colors = np.random.rand(100)  # 生成颜色
sizes = 1000 * np.random.rand(100)  # 生成大小

plt.scatter(x, y, c=colors, s=sizes, alpha=0.5)
plt.colorbar()  # 显示颜色条
plt.show()

柱状图绘制 🏗️

1
2
3
4
5
6
labels = ['苹果', '香蕉', '橙子', '梨']
values = [20, 35, 30, 15]

plt.bar(labels, values, color=['r', 'y', 'orange', 'g'])
plt.title('水果销量')
plt.show()

饼图绘制 🥧

1
2
3
4
5
6
7
8
labels = ['苹果', '香蕉', '橙子', '梨']
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)  # 突出显示香蕉

plt.pie(sizes, explode=explode, labels=labels, 
        autopct='%1.1f%%', shadow=True, startangle=90)
plt.axis('equal')  # 保证是圆形
plt.show()

3D 绘图 🔮

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)

ax.scatter(x, y, z, c='r', marker='o')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()

常见定制选项 🎨

参数 说明 示例值
color 颜色 ‘r’, ‘green’, ‘#FF00FF’
linestyle 线型 ‘-’, ‘–’, ‘:’, ‘-.’
linewidth 线宽 2, 3.5
marker 标记 ‘o’, ’s’, ‘^’, ‘+’
alpha 透明度 0.5, 1.0

保存图片 💾

1
2
plt.plot(range(10))
plt.savefig('my_plot.png', dpi=300, bbox_inches='tight')

记得保存图片后再 plt.show() 哦,因为 show() 会清除当前的图形对象呢!(◕‿◕✿)

祝你绘图愉快!✨

Licensed under CC BY-NC-SA 4.0
使用 Hugo 构建
主题 StackJimmy 设计