matplotlib可视化
模仿matlab构建,将数据进行可视化
import numpy as np
from matplotlib import pyplot as plt
简要绘图的简要参数设置
x = range(0,24,2)
height = np.linspace(0,24,12)
plt.plot(x,height)
plt.ylabel("height")
plt.xlabel('x')
plt.show()
plt.savefig('./photo.png')
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UxaGAhgY-1645436879919)(output_3_0.png)]
<Figure size 432x288 with 0 Axes>
常见问题
1. 使用savefig生成了图片,但打开图片后是空白的?
plt.savefig('./figure.png') #要在show()之前保存,否则即使生成了图片也是空白的内容
详细功能介绍
创建画板figure与轴Axes
pyplot适合简单的绘图,复杂的绘图工作使用figure+Axes
1. 一个个创建轴 ax = fig.add_subplot(XYx)
2. 一次型创建轴 fig,axes = plt.subplots(nrows=行数,ncols=列数)。
以数组形式访问轴
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set(xlim=[0.5, 4.5], ylim=[-2, 8],
title='subplot',
ylabel='Y轴', xlabel='X轴')
plt.show()
fig,axes = plt.subplots(nrows=2,ncols=2)
axes[0,0].set(title="0-0")
axes[1,1].set(title="1-1")
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LMOUfhUk-1645436879923)(output_7_0.png)]
[Text(0.5, 1.0, '1-1')]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2EhvYoZ4-1645436879924)(output_7_2.png)]
基本2D绘图
线
x = np.linspace(0,np.pi)
y_sin = np.sin(x)
y_cos = np.cos(x)
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(224)
ax1.plot(x,y_sin)
ax2.plot(x,y_sin,'go--',linewidth=2,markersize=12)
ax3.plot(x,y_cos,color='red',marker='+',linestyle='dashed')
[<matplotlib.lines.Line2D at 0x1bb33c83ac0>]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qbOSizxz-1645436879924)(output_9_1.png)]
x = np.arange(10)
y = np.random.randn(10)
plt.scatter(x,y,edgecolors='blue',marker='+')
plt.show()
C:\Users\27703\AppData\Local\Temp\ipykernel_70004\3730457368.py:4: UserWarning: You passed a edgecolor/edgecolors ('blue') for an unfilled marker ('+'). Matplotlib is ignoring the edgecolor in favor of the facecolor. This behavior may change in the future.
plt.scatter(x,y,edgecolors='blue',marker='+')
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dOP9lYax-1645436879926)(output_10_1.png)]
x = np.arange(5)
height = np.random.randn(5)
fig,axes = plt.subplots(ncols=2,figsize=plt.figaspect(1./2))
vert_bar = axes[0].bar(x,height,color='lightblue',align='center')
horiz_bar = axes[1].barh(x,height,color='lightblue',align='center')
axes[0].axhline(0,color='gray',linewidth=2)
axes[1].axvline(0,color='gray',linewidth=2)
plt.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MUSuZrfS-1645436879927)(output_11_0.png)]
fig, ax = plt.subplots()
vert_bars = ax.bar(x, height, color='lightblue', align='center')
for bar, height in zip(vert_bars, y):
if height < 0:
bar.set(edgecolor='darkred', color='salmon', linewidth=3)
plt.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zDOtCEWS-1645436879928)(output_12_0.png)]
n_bins = 10
x = np.random.randn(1000, 3)
fig, axes = plt.subplots(nrows=2, ncols=2)
ax0, ax1, ax2, ax3 = axes.flatten()
colors = ['red', 'tan', 'lime']
ax0.hist(x, n_bins, density=True, histtype='bar', color=colors, label=colors)
ax0.legend(prop={'size': 10})
ax0.set_title('bars with legend')
ax1.hist(x, n_bins, density=True, histtype='barstacked')
ax1.set_title('stacked bar')
ax2.hist(x, histtype='barstacked', rwidth=0.9)
ax3.hist(x[:, 0], rwidth=0.9)
ax3.set_title('different sample sizes')
fig.tight_layout()
plt.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AIE5oK8n-1645436879929)(output_13_0.png)]
labels = 'A', 'B', 'C', 'D'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)
colors = ['red','blue','orange','green']
fig, (ax1, ax2) = plt.subplots(2)
ax1.pie(sizes, labels=labels,colors=colors ,autopct='%1.1f%%', shadow=True)
ax1.axis('equal')
ax2.pie(sizes, autopct='%1.2f%%', shadow=True, startangle=90, explode=explode,
pctdistance=1.12)
ax2.axis('equal')
ax2.legend(labels=labels, loc='lower right')
plt.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lqJjkPaN-1645436879930)(output_14_0.png)]
data1 = np.random.randint(100,size=80)
data2 = data1.reshape(20,4)
fig,(ax1,ax2) = plt.subplots(2)
ax1.boxplot(data1)
ax2.boxplot(data2,vert=False)
fig.show()
C:\Users\27703\AppData\Local\Temp\ipykernel_70004\31056837.py:9: UserWarning: Matplotlib is currently using module://matplotlib_inline.backend_inline, which is a non-GUI backend, so cannot show the figure.
fig.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UeruTjdu-1645436879931)(output_15_1.png)]
x = np.random.rand(50)
y = np.random.rand(50)
colors = np.random.rand(50)
area = (30*np.random.rand(50))**2
plt.scatter(x,y,s=area,c=colors,alpha=0.5)
plt.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-R7dhAo64-1645436879932)(output_16_0.png)]
区间
调整X,Y区间
1. ax.set_xlim([xmin,xmax]) #设置x轴/y轴区间
2. ax.axis([xmin,xmax,ymin,ymax]) #设置XY区间
3. ax.set_xlim(right=25),ax.set_ylim(bottom=-10) #设置上下限
x = np.linspace(-2*np.pi,2*np.pi)
y = np.sin(x)
fig,(ax1,ax2) = plt.subplots(2)
ax1.plot(x,y)
ax1.set_xlim([-np.pi,np.pi])
ax2.plot(x,y)
ax2.set_xlim(left=-2*np.pi,right=2*np.pi)
plt.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sOp9PmYN-1645436879933)(output_18_0.png)]
图例说明
fig, ax = plt.subplots()
ax.plot(np.arange(4), [10, 20, 25, 30], label="xi'an")
ax.plot(np.arange(4), [30, 23, 13, 4], label="wuhan")
ax.scatter(np.arange(4), [20, 10, 30, 15], label='Point')
ax.set(ylabel='Temperature', xlabel='Time', title='2 cities')
ax.legend()
plt.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lUt98IQD-1645436879933)(output_20_0.png)]
区间分段
默认情况下,axes会自动控制区间分段
可以修改x轴的区间段,并修改x轴显示信息
data = [('chinese', 96), ('math', 99), ('english', 100)]
subject, score = zip(*data)
fig, (ax1, ax2) = plt.subplots(2)
x = np.arange(len(subject))
ax1.bar(x, score, align='center', color='gray')
ax2.bar(x, score, align='center', color='gray')
ax2.set(xticks=x, xticklabels=subject)
plt.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9dx1XumX-1645436879934)(output_22_0.png)]
|