matplotlib画图

听说用plt是异端,改用fig,ax了

💥画图常用命令

绘制多图/调整图幅大小/横纵坐标等间距

fig = plt.figure()
#将画布分为2行1列,共2个子图,并定位在第2个子图
ax = fig.add_subplot(222)

#括号里:宽、长(单位为inch)
#可能显示的时候不太明显,但figsize的设置可以在打印或者排版时发挥作用。
fig,ax=plt.subplots(figsize=(10,8))

ax.set_aspect('equal')

异端被我废弃⬇

import matplotlib.pyplot as plt
import numpy as np

x=np.linspace(-1,1,50)
y1=x**2
y2=x*2
#这个是第一个figure对象,下面的内容都会在第一个figure中显示
plt.figure()
plt.plot(x,y1)
#这里第二个figure对象
plt.figure(num = 3,figsize = (10,5))
plt.plot(x,y2)
plt.show()

更改坐标范围

#在plt.show()之前添加
plt.xlim((0,2))
plt.ylim((-2,2))
___________________________________________________________________
ax.set_xlim(0,20)
ax.set_ylim(0,11)  

plot的可选参数

颜色(color),点型(marker),线型(linestyle)

具体形式 fmt = '[color][marker][line]'

例如:

ax.plot(x, y, 'bo-')  # 蓝色圆点实线
ax.plot(x,y,color='green', marker='o', linestyle='dashed', linewidth=1, markersize=6)

也可以对关键字参数color赋十六进制的RGB字符串如 color='#900302'

常见颜色参数

character color
b
g 绿
r
c 蓝绿(cyan)
m 洋红(magenta)
y
k
w

颜色代码查询

常见线型(line)/点型(marker)参数

字符 描述
'-' 实线
'--' 虚线
'-.' 点线
':' 点虚线
'.'
',' 像素
'o' 圆形
'v' 朝下的三角形
'^' 朝上的三角形
'<' 朝左的三角形
'>' 朝右的三角形
'1' tri_down marker
'2' tri_up marker
'3' tri_left marker
'4' tri_right marker
's' 正方形
'p' 五角形
'*' 星型
'h' 1号六角形
'H' 2号六角形
'+' +号标记
'x' x号标记
'D' 钻石形
'd' 小版钻石形
'|' 垂直线型
'_' 水平线型

分别设置多条线的线型&点型(如果你调参要求多的话。。要是只改一般参数,在每组后边用‘bo-’这种缩写格式就好了)

#嗨,画线时候分开画不就完了,净整点没用的
import matplotlib.pyplot as plt
import numpy as np

x=np.arange(1,20)
y=x
y1=x**2
y2=x**0.5
fig,ax=plt.subplots()
lines = ax.plot(x, y, x, y1, x, y2, 'o')
#!设置线的属性
plt.setp(lines[0], linewidth=1)  
plt.setp(lines[1], linewidth=2)  
plt.setp(lines[2], linestyle='-',marker='^',markersize=4)
plt.show()
#分开画爽歪歪
import matplotlib.pyplot as plt
import numpy as np

x=np.arange(1,20)
y=x
y1=x**2
y2=x**0.5
fig,ax=plt.subplots()
ax.plot(x, y, linewidth=5)
ax.plot(x, y1,linewidth=2)
ax.plot(x, y2,linestyle='-',marker='^',markersize=4)
plt.show()

设置标签/坐标轴名称&范围/图的标题

#r'$   $':LaTeX格式,更美观
ax.legend([r'$$',r'$$'],loc=0,fontsize=40)
#设置坐标轴名称(单位),这俩字体都是斜体,一般用italic就行
ax.set_xlabel('XXX',fontsize=10,fontstyle='italic')
ax.set_ylabel('XXX',fontsize=10,fontstyle='oblique')
# 设定x,y
ax.set_xlim(0,20)
ax.set_ylim(0,11) 
#标题
ax.set_title('XXX',fontsize=18)

异端被我废弃⬇

plt.legend(['1','2','3'],loc='upper right',fontsize=40)
plt.xlabel("X轴")
plt.ylabel("Y轴") 
plt.title('标题') 

标签有几条线就写几个,[]可以换成()

位置:一般情况下,loc属性设置为'best'就足够应付了(直接写0也可以,loc=0)。

legend( handles=(line1, line2, line3),
       labels=('label1', 'label2', 'label3'),
       'upper right')
shadow = True 设置图例是否有阴影
The *loc* location codes are:
          '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

更改坐标名称

没写的数字就不会呈现

ax.set_xticks(range(0,21,5))
#修改坐标轴标签为文字
ax.set_xticklabels(list("abcdefg"))

异端被我废弃⬇

new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
#在对应坐标处更换名称
plt.yticks([-2,-1,0,1,2],['really bad','b','c','d','good'])

改成LaTeX样式(空格用'\ '转义):

plt.yticks([-2,-1,0,1,2],[r'$really\ bad$',r'$b$',r'$c\ \alpha$','d','good'])

3D图

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = Axes3D(fig)

#X Y value
X = np.arange(-4,4,0.25)
Y = np.arange(-4,4,0.25)
X,Y = np.meshgrid(X,Y)
R = np.sqrt(X**2 + Y**2)
#hight value
Z = np.sin(R)

#ax.set_xlabel('XXX')  #设置x轴标题,yz同理
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
"""
============= ================================================
        Argument      Description
        ============= ================================================
        *X*, *Y*, *Z* Data values as 2D arrays
        *rstride*     Array row stride (step size), defaults to 10
        *cstride*     Array column stride (step size), defaults to 10
        *color*       Color of the surface patches
        *cmap*        A colormap for the surface patches.
        *facecolors*  Face colors for the individual patches
        *norm*        An instance of Normalize to map values to colors
        *vmin*        Minimum value to map
        *vmax*        Maximum value to map
        *shade*       Whether to shade the facecolors
        ============= ================================================
"""

# I think this is different from plt12_contours
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.get_cmap('rainbow'))
"""
==========  ================================================
        Argument    Description
        ==========  ================================================
        *X*, *Y*,   Data values as numpy.arrays
        *Z*
        *zdir*      The direction to use: x, y or z (default)
        *offset*    If specified plot a projection of the filled contour
                    on this position in plane normal to zdir
        ==========  ================================================
"""
ax.set_zlim(-2, 2)
plt.show()
posted @ 2020-08-13 11:20  oNull  阅读(143)  评论(0)    收藏  举报