Python数据处理笔记matplotlib篇(一)

关键词:坐标轴范围,图像保存,坐标轴密度,axes自适应figure,matplotlib面向对象,部分理论概念

简单的小例子

1
2
3
4
5
6
7
8
9
10
11
12
import matplotlib.pyplot as plt
path = ""
plt.plot([4,7,1,9,4])
#绘图,如果只有一个list默认其为Y轴,X轴数据为其索引值
plt.ylabel("grade")
plt.axis([-2,8,0,12])
#axis函数接收一个list,设定横纵坐标尺度,list各个参数分别代表[X初始刻度,X终止刻度,Y起始刻度,Y终止 刻]
plt.savefig(path,dpi = 600)
#savefig函数用来保存图片至path地址,dpi值表示每英寸具有的像素点数
plt.show()
------
这个例子的关键词:坐标轴尺度、图像保存

plt.plot()简介:

1
2
3
4
5
6
7
8
9
10
11
plt.plot(x, y, format_string, **kwargs)
#这个函数是绘图的关键函数
#x : X轴数据,列表或数组,可选
#y : Y轴数据,列表或数组
#format_string : 控制曲线的格式字符串,可选
#**kwargs :第二组或更多(x,y,format_string)
其中要说明的是format_string,包含的主要类型有
颜色字符:'b','k'
风格字符:'-','--'
标记字符:每个数据点的标志方式,'.','*','o'
还要很多其他的参数值,到时候查文档

如何处理坐标轴的密度:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#设置密度之前,需要知道关于axis的一些内容
------
class matplotlib.axis.XAxis(axes, pickradius=15)
Init the axis with the parent Axes instance
------
class matplotlib.axis.YAxis(axes, pickradius=15)
Init the axis with the parent Axes instance
------
需要用父类Axes的实例对matplot.axis.XAxis进行初始化为一个axis实例(xaxis和yaxis都是axis的子类)
axis实例为axes_xaxis
fig,ax = plt.subplots()
axes_xaxis = matplotlib.axis.XAxis(ax)#ax是matplotlib.axes.Axes的一个实例
现在axes_xaxis就是一个Axis(XAxis)的实例

此处见过好多直接ax.xaxis.set_major……的使用方法,我的理解是,ax是一个父类的实例,可以直接调用任何的关于matplotlib.axis下的东西。有待考证(可用度不高,测试过,有的可,有的不可)

得出一个结论,能用plt就用plt,尽量不使用axes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#方法一:设置间隔法
axes_xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(5))#5代表每隔5个
------
#也可以不进行实例化,直接使用如下的方式
ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(5))
------
#方法二:自动线性调整
ax.xaxis.set_major_locator(ticker.LinearLocator(numticks=None, presets=None))
------
文档里LinearLocator的介绍
class matplotlib.ticker.LinearLocator(numticks=None, presets=None)
Bases: matplotlib.ticker.Locator
Determine the tick locations
The first time this function is called it will try to set the number of ticks to make a nice tick partitioning. Thereafter the number of ticks will be fixed so that interactive navigation will be nice
第一次调用的时候就会根据坐标轴的大小,自动的给设置好留几个tick_label合适
------

关键词:坐标轴,密度


axes自动填充满figure

1
2
mpl.rc('figure',autolayout = True)
#autolyout使axes自适应整个figure框

如何令图片文件名称与title一致

1
2
3
4
#首先设定了title的内容
ax.set_title('一程山路')
#然后保存图片是,图片的名称是这个即可
plt.savefig('%s.png'%(ax.get_title()),dpi = 300)#其中ax.get_title()即获取title

NOTICE:当使用了twinx()之后,尽量使用如下方式实现图片的保存

1
2
fig,ax = plt.subplots()
fig.savefig(path,**kwargs)#使用fig实例进行保存操作

#####关于matplotlib的面向对象

1
matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)

上面这个函数有两个返回值,他们分别如下:

1
2
fig : matplotlib.figure.Figure object
ax : matplotlib.axes.Axes object or array of Axes objects.

他们的关系由下图初见端倪:(fig是一个大面板,ax是这个面板上的区域,fig是由ax和其他一些东西组成的)

这两个类分别如下:

1
2
3
4
5
6
class matplotlib.figure.Figure(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None)
------
Figure:这个类的实例有很多的方法,如:
add_axes(*args, **kwargs)#添加一个axes,返回值是一个Axes实例
add_subplot(*args, **kwargs)#添加一个若干个axes,并返回一个Axes实例数组
------
1
2
3
4
5
6
7
8
class matplotlib.axes.Axes(fig, rect, facecolor=None, frameon=True, sharex=None, sharey=None, label='', xscale=None, yscale=None, axisbg=None, **kwargs)
------
Axes:这个类的方法有:
plot(*args,**kwargs)#实例使用此方法即能绘制图像,并且十分强大
scatter(*args,**kwargs)
还有与pyplot中一一对应的方法:
plt.xlabel()-->ax.set_xlabel()&ax.get_xlabel()#具体查文档
------

所以,小例子:

1
2
3
4
fig,ax = matplotlib.pyplot.subplots()
fig.set_size_inches((w,h))
ax.plot(x,y)
ax.set_xlabel("hello")
如何移轴
1
2
3
4
5
6
7
8
9
ax.spines['bottom'].set_position('center')
将地轴移到中间
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
把这些边框去掉
ax1.yaxis.set_ticks_position('left')
ax1.xaxis.set_ticks_position('bottom')
把tick移轴

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,8*np.pi,1000)
y = np.sin(x)
y1 = (x-x)
fig,ax = plt.subplots()
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_position('center')
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
ax.plot(x,y,x,y1)
fig.set_size_inches((8,2.5))
plt.show()

添加注释
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
mpl.rcParams['font.family'] = 'STFangsong'
x = np.linspace(0,8*np.pi,1000)
y = np.sin(x)
y1 = (x-x)
fig,ax = plt.subplots()
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_position('center')
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
# bagua = [乾兑离震巽坎艮坤]
------
bagua = ['乾','坤','兑','艮','离','坎','震','巽']
for i in range(8):
if i%2 == 0:
ax.annotate(bagua[i],(i*np.pi+np.pi/2-0.5,0.5),(i*np.pi+np.pi/2-0.4,0.5))
else:
ax.annotate(bagua[i],(i*np.pi+np.pi/2-0.5,-0.5),(i*np.pi+np.pi/2-0.4,-0.5))
------
ax.plot(x,y,x,y1)
fig.set_size_inches((8,2.5))
plt.show()

###理论概念


绘图区域设置

绘图区域概念如下:

在matplotlib中,一个独立的图像(不管有多少小图像)是一个Figure对象,一个Figure对象中可以包含一个或者多个Axes对象,每个Axes对象都是一个拥有自己独立坐标系统的绘图区域,如下:

因此,可以在全局绘图区域中创建一个分区体系,并定位到一个子绘图区域

1
2
3
4
plt.subplot(nrows,ncols,plot_number)
#区域分为nrows行,ncols列,现在绘制第plot_number个子图
plt.subplot(3,2,4)
#3行2列,选择第4个绘图区域,然后再使用plt.plot(参数)即可进行绘图了

一个Figure对应一张图片。Title为标题。Axis为坐标轴,Label为坐标轴标注。Tick为刻度线,Tick Label为刻度注释。