matplotlib-python可视化库

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=列数)。
        以数组形式访问轴
#创建figure画板
fig = plt.figure()

#在画板的第一行第一列的第一个位置生成一个ax对象
ax = fig.add_subplot(111)      #也可以(1,1,1)
ax.set(xlim=[0.5, 4.5], ylim=[-2, 8], 
        title='subplot',
       ylabel='Y轴', xlabel='X轴')
plt.show()

#一次性生成所有Axes,以二维数组形式访问
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')

# 在x轴上画线(水平/垂直方向)
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')

# We could have also done this with two separate calls to `ax.bar` and numpy boolean indexing.
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']

#1. histtype直方图样式,默认为bar,堆叠图barstacked
#2. density控制y轴表示x的频率/数量
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)
#autopct=%1.1f%%表示格式化百分比输出
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)]

## 箱型图
# help(plt.boxplot)
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)  #创建50个[0,1)均匀分布的数
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)   #返回区间内均匀分布的numbers
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)

#ax.tick_params(axis='y', direction='inout', length=10) #修改 ticks 的方向以及长度
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9dx1XumX-1645436879934)(output_22_0.png)]

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值