matplotlib总结

一般过程

图形创建

import matplotlib.pyplot as plt
f = plt.figure(num=2, figsize=(8,6), dpi=80, facecolor="pink", edgecolor="green", frameon=True)
f.suptitle(r"title")
#print(plt.setp(f))  查看可以设置的参数
Text(0.5, 0.98, 'title')




<Figure size 640x480 with 0 Axes>

创建子图

fig1=plt.subplot(1,2,1)     #借助plt创建

fig2=f.add_subplot(1,2,2)   #借助总图所返回的f对象
fig3=f.add_axes([0.1,0.1,0.5,0.5],facecolor='grey')

fig4=plt.axes([0.2,0.2,0.4,0.4],facecolor='green')
/root/anaconda3/envs/py36/lib/python3.6/site-packages/ipykernel_launcher.py:3: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance.  In a future version, a new instance will always be created and returned.  Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.
  This is separate from the ipykernel package so we can avoid doing imports until
/root/anaconda3/envs/py36/lib/python3.6/site-packages/ipykernel_launcher.py:4: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance.  In a future version, a new instance will always be created and returned.  Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.
  after removing the cwd from sys.path.

png

上面两种方法所返回的依然是Axes对象,只不过相比于前面的几种方法而言,Axes所放置的位置更加随意的,是任意放置的,通过[x,y,width,height],上面的四个值都是“相对取值”,故而在0~1之间,前面两个是以左下角作为基准的,后面两个数字指的是相对于整个figure对象的宽度和高度。

 其实我们对图像的自定义,主要就是对第二层对象Axes及其子对象的设置,第二层对象里面所包含的对象有一下一些常见的对象:

a、两条坐标轴xaxis yaxis及坐标轴标题

b、Title

c、图像(比如line曲线等)

d、Legend

e、Grid

f、Text

g、Annotation

网格系统

import matplotlib.pyplot as plt

plt.figure()
ax1 = plt.subplot2grid((3,3), (0,0), colspan=3, rowspan=1)
ax1.plot([1,2],[1,2])
ax1.set_title("ax1_title")
ax2 = plt.subplot2grid((3,3), (1,0), colspan=2)
ax3 = plt.subplot2grid((3,3), (1,2), rowspan=2)
ax4 = plt.subplot2grid((3,3), (2,0))
ax5 = plt.subplot2grid((3,3), (2,1))
plt.show()

png

import matplotlib.gridspec as gridspec
plt.figure()
gs = gridspec.GridSpec(3,3)
ax1 = plt.subplot(gs[0,:])
ax2 = plt.subplot(gs[1,:2])
ax3 = plt.subplot(gs[1:,2])
ax4 = plt.subplot(gs[-1,0])
ax5 = plt.subplot(gs[-1,-2])

png

坐标轴设置

所有ax对象的方法都是在plt对象方法前面加set

ax1.set_title("ax1_title") 等效于plt.title("ax1_title")

#(1)显示范围:
fig1.axis([xmin,xmax,ymin,ymax])
plt.axis([xmin,xmax,ymin,ymax])

#(2)分别设置x,y轴的显示范围:
fig1.set_xlim(2,4) 
fig1.set_ylim(2,4)
plt.xlim(2,4)   
Plt.ylim(2,4)

#(3)设置刻度:
fig1.set_yticks([-1,-1/2,0,1/2,1])  
fig1.xaxis.set_ticks([1,2,3,4,5,6,7,8])   #先获取x轴
#  这两种方法只能设置数字刻度

plt.xticks([0,np.pi/2,np.pi,3*np.pi/2,2*np.pi],['aaa','bbb','ccc','ddd','eee'],fontsize=‘xx-large’)
#这种方法可以将对应的数字用字符串替代出来

#若要显示π、α等一些特殊的数学符号,则可以通过以下来完成
plt.xticks([0,np.pi/2,np.pi,3*np.pi/2,2*np.pi],['$0$','$pi/2$','$pi$','$3pi/2$','$2pi$'],fontsize=‘xx-large’)
# ——该方法称之为LaTeX语法

#(4)坐标轴的显示和移动
# 默认坐标轴有四条,上下左右。
#(a)坐标轴不显示
zuobiao_zhou=plt.gca()  #获得坐标轴句柄,这是一种方式
zuobiao_zhou.spines['top'].set_color('none')
zuobiao_zhou_01=fig1.axes   #获得坐标轴对象,这是另一种方式
zuobiao_zhou_01.spines['right'].set_color('none')

#(b)设置刻度是显示在哪一条坐标轴旁边
zuobiao_zhou_01.yaxis.set_ticks_position('right')
zuobiao_zhou.xaxis.set_ticks_position('top')

#(5)设置主要-次要坐标轴
fig2=f.add_subplot(1,2,2)
line2,=plt.plot([1,2,3,4,5],[2,4,6,8,10],marker='>',label='第一条直线') 

#画图
plt.title('两条直线综合')                              #标题
fig2.legend(loc=2)                                   #图例
fig2.set_xlabel('横坐标')                             #设置坐标
fig2.set_ylabel('纵坐标一')
#-----------------------------------------------------------上面是主坐标系
fig3=fig2.twinx()             # 双胞胎,就是设置次坐标轴
line3=plt.plot([6,7,8,9,10],label='第二条直线')
fig3.legend(loc=1)
fig3.set_ylabel('纵坐标二')
#------------------------------------------------------------次要坐标系
plt.grid()                                 #网格
plt.show()
  File "<ipython-input-21-d5e45538495d>", line 16
    plt.xticks([0,np.pi/2,np.pi,3*np.pi/2,2*np.pi],['aaa','bbb','ccc','ddd','eee'],fontsize=‘xx-large’)
                                                                                          ^
SyntaxError: invalid character in identifier

tick_params语法

Axes.tick_params(axis='both', **kwargs)

参数:

  • axis : {‘x’, ‘y’, ‘both’} Axis on which to operate; default is ‘both’.
  • reset : bool If True, set all parameters to defaults before processing other keyword arguments. Default is False.
  • which : {‘major’, ‘minor’, ‘both’} Default is ‘major’; apply arguments to which ticks.
  • direction : {‘in’, ‘out’, ‘inout’} Puts ticks inside the axes, outside the axes, or both.
  • length : float Tick length in points.
  • width : float Tick width in points.
  • color : color Tick color; accepts any mpl color spec.
  • pad : float Distance in points between tick and label.
  • labelsize : float or str Tick label font size in points or as a string (e.g., ‘large’).
  • labelcolor : color Tick label color; mpl color spec.
  • colors : color Changes the tick color and the label color to the same value: mpl color spec.
  • zorder : float Tick and label zorder.
  • bottom, top, left, right : bool or {‘on’, ‘off’} controls whether to draw the respective ticks.
  • labelbottom, labeltop, labelleft, labelright : bool or {‘on’, ‘off’} controls whether to draw the respective tick labels.
  • labelrotation : float Tick label rotation

实例:

参数axis的值为'x'、'y'、'both',分别代表设置X轴、Y轴以及同时设置,默认值为'both'。

ax1.tick_params(axis='x',width=2,colors='gold')

ax2.tick_params(axis='y',width=2,colors='gold')

ax3.tick_params(axis='both',width=2,colors='gold')

坐标轴边框

  • gca():获取当前坐标轴信息
  • spines:设置边框
  • set_color:设置边框颜色:默认白色
  • spines:设置边框
  • xaxis.set_ticks_position:设置x坐标刻度数字或名称的位置
  • yaxis.set_ticks_position:设置y坐标刻度数字或名称的位置
  • set_position:设置边框位置

ax = plt.gca()

设置上边和右边无边框

ax.spines['right'].set_color('none')

ax.spines['top'].set_color('none')

获取坐标轴刻度对象

Matplotlib 中的 ticker 模块用于支持坐标轴刻度的修改,调用下列命令可以初步查看主副坐标轴刻度的数值定位方式(locator)与具体格式(formatter)等。

详细命令参考:http://matplotlib.org/api/axis_api.html

  • ax.xaxis.get_major_ticks()
  • ax.xaxis.get_minor_ticks()
  • ax.xaxis.get_major_locator()
  • ax.xaxis.get_minor_locator()
  • ax.xaxis.get_major_formatter()
  • ax.xaxis.get_minor_formatter()

设置主副刻度对象属性

设置主副刻度格式

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

t = np.arange(0.0, 100.0, 1)
s = np.sin(0.1*np.pi*t)*np.exp(-t*0.01)
ax = plt.subplot(111) #注意:一般都在ax中设置,不再plot中设置
plt.plot(t,s,'--r*')

#修改主刻度
xmajorLocator = MultipleLocator(20) #将x主刻度标签设置为20的倍数
xmajorFormatter = FormatStrFormatter('%5.1f') #设置x轴标签文本的格式
ymajorLocator = MultipleLocator(0.5) #将y轴主刻度标签设置为0.5的倍数
ymajorFormatter = FormatStrFormatter('%1.1f') #设置y轴标签文本的格式
#设置主刻度标签的位置,标签文本的格式
ax.xaxis.set_major_locator(xmajorLocator)
ax.xaxis.set_major_formatter(xmajorFormatter)
ax.yaxis.set_major_locator(ymajorLocator)
ax.yaxis.set_major_formatter(ymajorFormatter)
#修改次刻度
xminorLocator = MultipleLocator(5) #将x轴次刻度标签设置为5的倍数
yminorLocator = MultipleLocator(0.1) #将此y轴次刻度标签设置为0.1的倍数
#设置次刻度标签的位置,没有标签文本格式
ax.xaxis.set_minor_locator(xminorLocator)
ax.yaxis.set_minor_locator(yminorLocator)

#打开网格
ax.xaxis.grid(True, which='major') #x坐标轴的网格使用主刻度
ax.yaxis.grid(True, which='minor') #y坐标轴的网格使用次刻度
plt.show()

png

删除坐标轴的刻度显示

ax.yaxis.set_major_locator(plt.NullLocator())

ax.xaxis.set_major_formatter(plt.NullFormatter())

线条相关的设置

#(1)关闭抗锯齿  
line1.set_antialiased(False)

#(2)线条样式的各种设置——四种设置方法
#方法一:直接在画线的时候通过“字符串参数”加以指定
line1,=fig1.plot(x,y,'r-')  #简单设置可以这样使用

#方法二:直接在划线的时候通过参数指定,如下:
line1,=fig1.plot(x,y,color='red',linewidth=3,linestyle='--')

#方法三:通过line.set_xxxx()的方式加以设置,如下:
line1,=fig1.plot(x,y1)
line1.set_color('black')
line1.set_linestyle('-')
line1.set_alpha(0.3)
line1.set_linewidth(8)

#方法四:通过plt.setp(line,xxxxxxxxx)方法去设置
plt.setp(line1,color='black',linewidth=8,linestyle='-',alpha=0.3)

'''推荐使用二三四种方法。
注意,设置线条样式的属性非常的多,我们可以通过以下方式加以查看'''
Print(plt.setp(line))   #会显示到底有哪些属性可以设置

#(3)下面是常见的属性设置:
'''常见的颜色:——除了使用字母,还可以使用十六进制的字符串表示,比如“#008000”,这样任意一种颜色均可以使用了。
        ``'b'``          blue
        ``'g'``          green
        ``'r'``          red
        ``'c'``          cyan(青色)
        ``'m'``          magenta(品红)
        ``'y'``          yellow
        ``'k'``          black
        ``'w'``          white
常见的线型:
        ``'-'``          solid line style
        ``'--'``         dashed line style
        ``'-.'``         dash-dot line style
        ``':'``          dotted line style
常见的点标记marker:
 '.'       point marker
','       pixel marker
'o'       circle marker
'v'       triangle_down marker
'^'       triangle_up marker
'<'       triangle_leftmarker
'>'       triangle_rightmarker
'1'       tri_down marker
'2'       tri_up marker
'3'       tri_left marker
'4'       tri_right marker
's'       square marker
'p'       pentagon marker
'*'       star marker
'h'       hexagon1 marker
'H'       hexagon2 marker
'+'       plus marker
'x'       x marker
'D'       diamond marker
'd'       thin_diamond marker
'|'       vline marker
'_'      hline
'''

图例相关设置

#(1)设置图例的几种方式
    #方式一:在画线的时候设置label,调用legend函数即可。
    #方式二: 
line1.set_label("正弦曲线")         #确定图例
fig1.legend(['正弦','余弦'],loc='upper left')
    #方式三:
legend((line1,line2, line3), ('label1', 'label2', 'label3'))

#(2)legend()图例显示的位置
#(3)loc :表示图例显示的位置
   '''===============   =============
        Location String   Location Code
      ===============   =============
        'best'            0
        'upper right'     1
       'upper left'      2
         'lower left'      3
        'lower right'     4
          'right'           5
         'center left'     6
          'center right'    7
         'lower center'    8
           'upper center'    9
            'center'          10

 (4)其他参数设置
        facecolor='green',
        edgecolor=‘black’
        frameon=True,
        shadow=True,
        framealpha=0.5,
        fontsize='xx-large'
等等
'''
  File "<ipython-input-23-e2d806d42f66>", line 11
    '''===============   =============
    ^
IndentationError: unexpected indent

与标题相关的设置

'''
(1)  两种设置的方式
    方式一: fig1.set_title("这是第一幅图")      #设置标题
    方式二: plt.title('这是第二幅图') 
(2)其他参数的设置
        loc : {'center', 'left', 'right'},设置标题显示的位置
        pad :float  设置标题距离图像上边缘有多远
        fontsize:设置字体大小,如‘xx-large’
        color='red'设置字体颜色
'''

网格

'''
which='major',给主坐标还是次坐标
axis='x',       只显示哪一个轴或者是两者
color='r',     颜色
linestyle='-',   线型
linewidth=2   线粗
'''

文本及注释

文本

#两种设置方式均可,即
    #方式一:
fig.text(x,y,s)
    #方式二:
plt.text(x,y,s).

'''其中,x,y表示的是文本插入的位置,s表示的是文本的内容,还有一些常见的可选参数如下:
    Alpha=0.5
    color='green',
    backgroundcolor=‘yellow’
    fontsize=15,(可以简写为size)
    fontstyle=20(可以简写为style)
    rotation='60',表示文本旋转多少度
    fontweight='bold',(可以简写为weight)取值可以是(normal bold heavy light ultrabold ultralight)
    family=‘serif’ 字体
    linespace=1.5  字体行距
    horizontalalignment=‘center’ x参数表示的位置(也可以简写为ha)取值可以是(center right left)
    verticalalignment=‘center’  y参数表示的位置(简写为va)取值可以是(center top bottom baseline)
    multialignment=‘center’ 多行位置控制 取值可以是(center right left)
注意:最后三个参数负责布局的控制'''

#(1) 设置文本的边框——通过设定bbox来完成
    #方式一:
bbox_props =dict(boxstyle="rarrow", fc="red", ec="0.5",alpha=0.9,pad=0.6)
plt.text(参数列表,bbox=bbox_props) 通过设定bbox参数来完成,
    #方式二:
text_01=plt.text()  #首先返回文本对象
Text_01.set_bbox1(bbox_props)

注释

 #两种设置方式均可,即
 #方式一:
fig.annotate(s,xy=(3,4),xytext=(3,6))
#方式二:
plt. annotate(s,xy=(3,4),xytext=(3,6))

'''其中,xy表示的是注释插入的位置,s表示的是文本的内容,xytext表示的是注释的文本的位置,还有一些常见的可选参数如下:
其他的一些常用参数如下:
 xycoords : 箭头所使用的坐标系
            'figurepoints'   points from the lower left ofthe figure
            'figure pixels'     pixels from the lower left of the figure
            'figure fraction'   fraction of figure from lower left
            'axes points'      points from lower left corner of axes
            'axes pixels'       pixels from lower left corner of axes
            'axes fraction'     fraction of axes from lower left
           'data'          use the coordinate system of theobject being annotated (default)
            'polar'          (theta,r) if not native 'data'coordinates
  textcoords : 文字所使用的坐标系
            'offsetpoints'    offset (in points) from thexy value
            'offsetpixels'     offset (in pixels) from thexy value
                                defaults  to the input of xycoords(默认的和xycoords一样)
bbox:设置注释文字的边框,同上面的文本text是一样的。
arrowprops : 箭头样式设置,必须是字典类型的
            width   the width of the arrow in points
            headwidth   the width of the base of the arrowhead in points
            headlength  the length of the arrow head in points
            shrink       fraction of total length to 'shrink'from both ends
            color  设置颜色
            arrowstyle  设置箭头样式
            connectionstyle设置箭头和文本连接的样式
            connectionstyle的取值可以为(angle  angle3    arc  arc3 bar )
              arrowstyle 的取值可以为('-'   '->'  '-['   '|-|'  '-|>'  '<-'  '<->'  '<|-'
                                                             '<|-|>'   'fancy'  'simple'  'wedge')
'''
原文地址:https://www.cnblogs.com/qian-shan/p/12591250.html