Matplotlib库学习笔记

Matplotlib库

Matplotib库类似matlab,是Python中用于绘图的库,可以根据给定数据绘制出各种图表、函数动画等,将数据可视化更有利于对数据进行系统的分析。

引入Matplotlib库pyplot模块

import matplotlib.pyplot as plt

后使用时简称为plt

绘制与编辑图像

plot以及Figure窗口

在plt模块里,我们可以直接用plot绘制出图像 (同时引用numpy库)

import numpy as np
p=np.pi
x=np.arange(0, 2*p, 0.001)
y=np.sin(x)
plt.plot(x,y)
plt.show()                    #输出图像的执行语句

这样我们就得到了sin函数的部分图像,x的范围则是我们定义的0到2派;输出图像的是Figure窗口,如图可对图像视图进行操作

image-20221028191259895

可以对坐标轴可以进行更改,更改他们的初始单位长度,并给予他们名字; 同时可以增加标题:

p=np.pi
x=np.arange(0, 2*p, 0.001)
y=np.sin(x)
plt.plot(x,y)
plt.title('sin x')			#添加标题
plt.xlabel('x')
plt.ylabel('y')				#设置x、y轴名字
plt.xlim(-2*p,2*p)
plt.ylim(-2,2)				#设置x、y的初始单位长度以及区间
plt.show()

image-20221028201227101

使用 plt.xticks(数组),plt.yticks(数组) 可以对x、y坐标轴显示的初始值

p=np.pi
x=np.arange(0, 2*p, 0.001)
y=np.sin(x)
plt.plot(x,y)
plt.show() 

p=np.pi
n=np.linspace(0,6,4)
x=np.arange(0, 2*p, 0.001)
y=np.sin(x)
plt.xticks(n)
plt.plot(x,y)
plt.show()

p=np.pi
x=np.arange(0, 2*p, 0.001)
y=np.sin(x)
plt.xticks([0,2,4,6],
           ['A','L','WAN','SUI'])	#对坐标值进行替换
plt.plot(x,y)
plt.show()

image-20221028203342512

image-20221028203416102

image-20221028204352884

x坐标轴显示的初始值发生了改变

Axes

对于 plot,写入坐标轴需要分别写入;而 Axes 使用 set 可以直接在一行语句中写入需要更改的东西,而且使用 plt.plot 的作画方式只适合简单的绘图,快速的将图绘出。在处理复杂的绘图工作时,我们还是需要使用 Axes 来完成作画的。

fig=plt.figure()					#插入“画布”
ax=fig.add_subplot(111)				#这里的‘111’表示:在画板的第1行第1列的第一个位置生成一个Axes对象来准备作画
p=np.pi
x=np.arange(0, 2*p, 0.001)
y=np.sin(x)
ax.set(xlabel='x',ylabel='y',xlim=[-2*p,2*p],ylim=[-2,2],title='sin x')
ax.plot(x,y)
plt.show()

效果同上

对于现实的数据分析,画出一个图是不够的,所以会在一个画布中同时生成多个Axes对象,便于进行对比分析

fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(224)
plt.show()

image-20221028201805571

图像性质与legend图示

便于进行对比分析,通常也会把两个图像放在同一个axe里,我们需要区分图线,并且设置legend图示:

ax_1=fig.add_subplot(111)
x=np.arange(0.1, 5, 0.001)
y_1 = x**3
y_2 = x**(-1)
ax_1.set(xlim=(0,5), ylim=(0,10))
l1, = ax_1.plot(x,y_1,label='^3')
l2, = ax_1.plot(x,y_2,label='^-1',color='red')
plt.legend(handles=[l1,l2,]) 		#设置图示
plt.show()

image-20221028210250673

  • 代码中 l1,l2, 中的 “ , ” 一定要加!否则会报错。
  • label参数用来定义函数图线的名字
  • color参数用来设置图线的颜色,另外
  • linestyle参数可以设置函数图线的线种类 (有:“-”(实线),“–”(划虚线),“:” (点虚线) )
  • linewidth参数可以设置图线的粗细

改变轴的位置,交点的位置,去掉边框,使图像更加像一个数学函数图像

ax = plt.gca()
ax.spines['top'].set_visible(False)     #顶边界不可见
ax.xaxis.set_ticks_position('bottom')   #ticks的位置为下方,分上下的。
ax.spines['right'].set_visible(False)   #右边界不可见
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
plt.show()

image-20221029010653535

Annotation标注

从函数上的某一点标注出虚线指到坐标轴,可以这样

fig=plt.figure()
ax=fig.add_subplot(111)
x=np.arange(0.1, 5, 0.001)
y = x**3
x0=1
y0=x0**3
ax.set(xlim=(0,5), ylim=(0,10))
ax.plot(x,y,label='^3')
ax.plot([x0,x0],[0,y0],linestyle='--',color='k')
ax.plot([0,x0],[y0,y0],linestyle='--',color='k')
plt.show()

image-20221029094917022

使用annotate来标注图像的特征点

ax.annotate('?',xy=(x0,y0),xytext=(2,0.5),fontsize=16,
            arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=0.2',color='blue'))
#第一个‘?’,表示了想要返回的描述文本
#xy=(,)表示了箭头指向的终点
#xytext=(,)表示了返回的描述文本的起始点
#arrowprops是箭头的相关参数字典
plt.show()

image-20221029104113773

以下来自原文:Matplotlib 中文用户指南 4.5 标注_布客飞龙的博客-优快云博客

arrowprops参数
arrowprops描述
width箭头宽度,以点为单位
frac箭头头部所占据的比例
headwidth箭头的底部的宽度,以点为单位
shrink移动提示,并使其离注释点和文本一些距离
**kwargsmatplotlib.patches.Polygon的任何键,例如facecolor
connectionstyle键 (决定连接的线的路径)
名称属性
angleangleA=90,angleB=0,rad=0.0
angle3angleA=90,angleB=0
arcangleA=0,angleB=0,armA=None,armB=None,rad=0.0
arc3rad=0.0
bararmA=0.0,armB=0.0,fraction=0.3,angle=None

image-20221029201759615

箭头补丁,arrowstyle
名称属性
-None
->head_length=0.4,head_width=0.2
-[widthB=1.0,lengthB=0.2,angleB=None
|-|widthA=1.0,widthB=1.0
-|>head_length=0.4,head_width=0.2
<-head_length=0.4,head_width=0.2
<->head_length=0.4,head_width=0.2
<|-head_length=0.4,head_width=0.2
<-|>
fancyhead_length=0.4,head_width=0.4,tail_width=0.4
simplehead_length=0.5,head_width=0.5,tail_width=0.2
wedgetail_width=0.3,shrink_factor=0.5

img

图像种类

散点图

用 scatter 函数,可以看出数据的分布、密集程度

x = np.arange(10)
y = np.random.randn(10)
plt.scatter(x, y, marker='+')
plt.show()

image-20221029105723663

散点图可以升级为 泡泡图

折线图

折线图可以看出数据的变化

fig=plt.figure()
ax=fig.add_subplot(111)
x=np.arange(0,10)
y=np.random.randn(10)
ax.plot(x,y)
plt.show()

image-20221029161217552

通过grid函数,添加网格,让数据更明显

fig=plt.figure()
ax=fig.add_subplot(111)
x=np.arange(0,10)
y=np.random.randn(10)
plt.grid()
ax.plot(x,y)
plt.show()

image-20221029161439374

柱状图

使用bar,来绘制出柱状图

fig=plt.figure()
ax=fig.add_subplot(111)
x=np.arange(5)
y1=np.random.uniform(0.5,1.0,5)
y2=np.random.uniform(0.5,1.0,5)
ax.bar(x,y1,facecolor='pink',edgecolor='white')
ax.bar(x,-y2,facecolor='c',edgecolor='white')
plt.show()

image-20221029163756106

下进行优化

fig=plt.figure()
ax=fig.add_subplot(111)
x1=np.arange(5)
y1=np.random.uniform(0.5,1.0,5)
y2=np.random.uniform(0.5,1.0,5)
ax.set(xlim=(-1,5),ylim=(-2,2))
ax.bar(x1,y1,facecolor='pink',edgecolor='white')
ax.bar(x1,-y2,facecolor='c',edgecolor='white')

for x,y in zip(x1,y1):
    ax.text(x,y+0.05,'%.2f'%y,ha='center')
for x,y in zip(x1,y2):
    ax.text(x,-y-0.1,'%.2f'%y,ha='center')

plt.show()

image-20221029165902627

通过 barh,我们可以画出水平的柱状图

fig,ax=plt.subplots(ncols=2,figsize=plt.figaspect(1/2))   		#设置两个axes,一个占整个fig的二分之一
x=np.arange(5)
y1=np.random.uniform(0.5,1.0,5)
y2=np.random.uniform(0.5,1.0,5)
ax[0].bar(x,y1,facecolor='pink',edgecolor='white')
ax[1].barh(x,-y2,facecolor='c',edgecolor='white')
plt.show()

image-20221029170706783

饼图
labels='A','B','C','D'
score=[10,30,40,20]
fig=plt.figure()
ax=fig.add_subplot(111)
ax.pie(score,labels=labels,autopct='%1.1f%%',shadow=True)	#autopct是标在饼上的百分比;shadow是阴影,默认False
plt.show()

image-20221029171509214

对其进行美化

labels='A','B','C','D'
score=[10,30,40,20]
explode = (0.1, 0, 0, 0)
fig=plt.figure()
ax=fig.add_subplot(111)
ax.pie(score,autopct='%1.1f%%',shadow=True,explode=explode,pctdistance=1.2)   #explode是突出哪一块,pctdistance是设定autopct距离饼图圆心的距离
ax.legend(labels=labels,loc='best')
plt.show()

image-20221029201452272

热力图

通过对色块着色来显示数据的统计图表,每个色块表示数据的大小

可以将一个二维数组输入到imshow函数来绘制出一个热力图

points=np.random.randn(100).reshape(10,10)
plt.imshow(points)
plt.tight_layout()
plt.colorbar() #添加数值和颜色的对应规则图示
plt.show()

image-20221029200431796

通过tick也是可以更改坐标数值的

(x _ x)好多制图类型好多参数呜(x _ x)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值