画图一直都是我的弱项,每次建模运行出结果却不知道如何实现可视化~希望通过这篇文章好好整理总结一下:
函数图像
import numpy as np
import matplotlib.pyplot as plt
# 指定开始值、终值和元素个数创建一维等差数组
x = np.linspace(-np.pi, np.pi, 1000)
# 两个函数表达式
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
# 需要标注的点
xo = np.pi * 3 / 4
yo_cos = np.cos(xo) / 2
yo_sin = np.sin(xo)
# 设置x,y轴坐标范围,乘1.1是为了给上下左右留出一点空间
plt.xlim(x.min() * 1.1, x.max() * 1.1)
plt.ylim(sin_y.min() * 1.1, sin_y.max() * 1.1)
# plt.xticks() 设置坐标刻度标签
plt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2,
np.pi * 3 / 4, np.pi],
[r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$',
r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$',
r'$\pi$'])
plt.yticks([-1, -0.5, 0.5, 1])
# plt.gca()获取当前的坐标轴
ax = plt.gca()
# 将左边与底部的坐标轴移至原点,上右两个坐标轴设置颜色为无,即转换为十字坐标轴
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 绘制两条实线曲线
plt.plot(x, cos_y, linestyle='-', linewidth=2,
color='dodgerblue',
label=r'$y=\frac{1}{2}cos(x)$')
plt.plot(x, sin_y, linestyle='-', linewidth=2,
color='orangered', label=r'$y=sin(x)$')
# 用虚线连接两个标注的点
plt.plot([xo, xo], [yo_cos, yo_sin], linestyle='--',
linewidth=1, color='limegreen')
# 绘制两个标注的点
plt.scatter([xo, xo], [yo_cos, yo_sin], s=60,
edgecolor='limegreen',
facecolor='white', zorder=3)
# 备注
plt.annotate(
r'$\frac{1}{2}cos(\frac{3\pi}{4})=-\frac{\sqrt{2}}{4}$',
xy=(xo, yo_cos), xycoords='data',
xytext=(-90, -40), textcoords='offset points',
fontsize=14,
arrowprops=dict(
arrowstyle='->',
connectionstyle='arc3, rad=0.2'))
plt.annotate(
r'$sin(\frac{3\pi}{4})=\frac{\sqrt{2}}{2}$',
xy=(xo, yo_sin), xycoords='data',
xytext=(20, 20), textcoords='offset points',
fontsize=14,
arrowprops=dict(
arrowstyle='->',
connectionstyle='arc3, rad=0.2'))
# 添加图例,位置在左上角
plt.legend(loc='upper left')
plt.show()
下图为输出图像:
- plot()、scatter() 等函数里添加label参数,才能在图例中显示
- 注释函数:
plt.annotate(备注文本, xy=目标位置, xycoords=对目标位置的说明, xytext=备注位置, textcoords=对备注位置的说明, fontsize=字体大小, arrowprops=箭头属性)
xycoords='data'
是说基于数据的值来选位置,xytext=(-90, -40), textcoords='offset points'
表示对于标注位置的描述 和 xy 偏差值,即标注位置是 xy 位置向左移动 90,向下移动40
创建图形对象
图形对象:plt.figure(对象名, figsize=大小, dpi=分辨率, facecolor=颜色)
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 1000)
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
# 创建图形对象
plt.figure('Sin', figsize=(3, 2), dpi=200, facecolor='dodgerblue')
# 添加图像标题
plt.title('Sin', fontsize=20)
# 添加横纵坐标标签
plt.xlabel('Sin', fontsize=14)
plt.ylabel('y=sin(x)', fontsize=14)
# 设置坐标轴刻度标签大小
plt.tick_params(labelsize=10)
# 添加网格线
plt.grid(linestyle=':')
plt.plot(x, sin_y, c='orangered', label=r'$y=sin(x)$')
plt.legend()
plt.show()
输出图像如下:
添加子图
plt.figure('Subplot', facecolor='lightgray')
# 添加子图
plt.subplot(221)
# 不显示横纵坐标刻度
plt.xticks(())
plt.yticks(())
# 无指向型注释text()
plt.text(0.5, 0.5, '1', ha='center', va='center', size=36, alpha=0.5)
plt.subplot(222)
plt.xticks(())
plt.yticks(())
plt.text(0.5, 0.5, '2', ha='center', va='center', size=36, alpha=0.5)
plt.subplot(223)
plt.xticks(())
plt.yticks(())
plt.text(0.5, 0.5, '3', ha='center', va='center', size=36, alpha=0.5)
plt.subplot(224)
plt.xticks(())
plt.yticks(())
plt.text(0.5, 0.5, '4', ha='center', va='center', size=36, alpha=0.5)
plt.show()
plt.subplot(nrows, ncols, index, **kwargs)
:位置是由三个整型数值构成,第一个代表行数,第二个代表列数,第三个代表索引位置。举个栗子:plt.subplot(2, 3, 5) 和 plt.subplot(235) 是一样一样的。plt.text(x, y, s, fontdict=None, withdash=<deprecated parameter>, **kwargs)
添加纯文本的注释,第一个参数是x轴坐标,第二个参数是y轴坐标,第三个参数是要显式的内容.
输出图形如下:
栅格布局
import matplotlib.gridspec as mg
plt.figure('Subplot', facecolor='lightgray')
# 获取栅格定位器
gs = mg.GridSpec(3, 2)
# 第一个子图的位置为第1行,并占满所有列
plt.subplot(gs[0, :])
# 取消坐标刻度
plt.xticks(())
plt.yticks(())
# 添加注释文本
plt.text(0.5, 0.5, '1', ha='center', va='center', size=36, alpha=0.5)
# 第二个子图的位置,横向占满第2行至第3行,纵向为第1列
plt.subplot(gs[1:,0])
plt.xticks(())
plt.yticks(())
plt.text(0.5, 0.5, '2', ha='center', va='center', size=36, alpha=0.5)
# 第三个子图的位置,第2行,第2列
plt.subplot(gs[1,1])
plt.xticks(())
plt.yticks(())
plt.text(0.5, 0.5, '3', ha='center', va='center', size=36, alpha=0.5)
# 第四个子图的位置,第3行,第2列
plt.subplot(gs[2,1])
plt.xticks(())
plt.yticks(())
plt.text(0.5, 0.5, '4', ha='center', va='center', size=36, alpha=0.5)
#自动调整子图参数,使之填充整个图像区域
plt.tight_layout()
plt.show()
mg.GridSpec(行数,列数)
用来获取栅格定位器;plt.tight_layout()
会检查坐标轴标签、刻度标签以及标题的位置,起到紧致布局的作用
图像如下:
自由布局
plt.figure('Axes', facecolor='lightgray')
# 百分比
plt.axes([0.03, 0.038, 0.94, 0.924])
plt.xticks(())
plt.yticks(())
plt.text(0.5, .5, '1', ha='center', va='center', size=36, alpha=0.5)
plt.axes([0.63, 0.076, 0.31, 0.308])
plt.xticks(())
plt.yticks(())
plt.text(0.5, .5, '2', ha='center', va='center', size=36, alpha=0.5)
plt.tight_layout()
plt.show()
plt.axes()
获取子图的轴域,axes([left, bottom, width, height])
其中上下左右的值是相对原点而言的,以百分比表示
图形如下:
坐标刻度
plt.figure('Locator')
# 获取定位器对象
locators = [
'plt.NullLocator()', # 空刻度定位器
'plt.MaxNLocator(nbins=5, steps=[1, 3, 5, 7, 9])',# 指定最多刻度数?
'plt.FixedLocator(locs=[0, 2.5, 5, 7.5, 10])', #由参数指定刻度
'plt.AutoLocator()', # 自动分配刻度值位置
'plt.IndexLocator(offset=0.5, base=1.5)', #根据偏移和增量定位刻度
'plt.MultipleLocator()',# 根据指定的距离定位刻度
'plt.LinearLocator(numticks=21)',# 线性划分20等分,21个刻度
'plt.LogLocator(base=2, subs=[1.])',# 根据指定的底数和指数定位刻度
]
n_locators = len(locators)
for i, locator in enumerate(locators):
# 创建子图
plt.subplot(n_locators, 1, i + 1)
# 设置横纵坐标范围
plt.xlim(0, 10)
plt.ylim(-1, 1)
plt.yticks(())
ax = plt.gca()
# 不显示左边顶部与右边的坐标轴
ax.spines['left'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
# 将底部的坐标轴移植原点位置
ax.spines['bottom'].set_position(('data', 0))
# 设置主刻度
ax.xaxis.set_major_locator(eval(locator))
# 设置次刻度
ax.xaxis.set_minor_locator(mp.MultipleLocator(0.1))
plt.plot(np.arange(0, 11), np.zeros(11), c='none')
# 添加文本注释
plt.text(5, 0.3, locator[3:], ha='center', size=10)
plt.tight_layout()
plt.show()
ax = mp.gca() # 获取坐标轴
ax.xaxis.set_major_locator(坐标定位器对象) # 主刻度
ax.xaxis.set_minor_locator(坐标定位器对象) # 次刻度
图形如下:
散点图
import numpy as np
n = 1000
# 生成n个服从均值为0,标准差为1的高斯分布随机数
x = np.random.normal(0, 1, n)
# 生成n个服从均值为0,标准差为1的高斯分布随机数
y = np.random.normal(0, 1, n)
z = np.sqrt(x ** 2 + y ** 2)
plt.figure('Scatter', facecolor='lightgray')
# 刻度标签大小设为10
plt.tick_params(labelsize=10)
# 设置x轴的坐标刻度为-2~2,间隔为1
plt.xticks(range(-2, 3, 1))
# 添加网格线
plt.grid(linestyle=':')
# 绘制散点
plt.scatter(x, y, s=60, c=z, cmap='jet_r', alpha=0.5)
# 设置xy轴等比,画出来的圆不变形
plt.axis('equal')
plt.show()
scatter(水平坐标, 垂直坐标, s=大小, c=颜色, cmap=颜色映射,
marker=点型, alpha=透明度, label=标签)
图形如下:
条形图
n = 12
x = np.arange(n)
#np.random.uniform():从一个均匀分布[low,high)中随机采样n个点
y1 = (1 - x / n) * np.random.uniform(0.5, 1.0, n)
y2 = (1 - x / n) * np.random.uniform(0.5, 1.0, n)
plt.figure('Bar', facecolor='lightgray')
plt.title('Bar', fontsize=20)
plt.ylim(-1.25, 1.25)
# 设置x,y轴标签与标签大小
plt.xlabel('x', fontsize=14)
plt.ylabel('y', fontsize=14)
# 添加x轴刻度(从1开始)
plt.xticks(x, x + 1)
plt.tick_params(labelsize=10)
# 设置y轴的网格线
plt.grid(axis='y', linestyle=':')
# 绘制条形图
plt.bar(x, y1, ec='white', fc='dodgerblue',
label='Sample 1')
for _x, _y in zip(x, y1):
plt.text(_x, _y, '%.2f' % _y,
ha='center', va='bottom', size=8)
plt.bar(x, -y2, ec='white', fc='dodgerblue',
alpha=0.5, label='Sample 2')
for _x, _y in zip(x, y2):
plt.text(_x, -_y - 0.015, '%.2f' % _y,
ha='center', va='top', size=8)
# 添加图例
plt.legend()
plt.show()
条形图bar(水平坐标, 高度, ec, fc, label)
ec为边缘色,fc为填充色
图形如下:
饼图
values = [26, 17, 21, 29, 11]
spaces = [0.05, 0.01, 0.01, 0.01, 0.01]
labels = ['Python', 'JavaScript', 'C++', 'C', 'PHP']
colors = ['dodgerblue', 'orangered', 'limegreen',
'violet', 'gold']
plt.figure('Pie', facecolor='lightgray')
plt.title('Pie', fontsize=20)
# 绘制饼图
plt.pie(values, spaces, labels, colors, '%d%%',
shadow=True, startangle=90)
plt.axis('equal')
plt.show()
plt.pie(值, 间隙, 标签, 颜色, 格式, shadow, startangle)
shadow = True 为饼状图添加阴影
startangle:若不是None,则饼图的起点为 x 轴并逆时针旋转 angle 度
图形如下:
持续更新中~
若是文章中出现错误,欢迎指正~