matplotlib 绘图基础

本文总结了常用的 matplotlib 绘图操作,以便于查阅。

  1. 绘制函数图

  2. 坐标轴设置

  3. 文字设置

  4. 绘制多幅子图

  5. 特殊形状

  6. 非线性坐标轴

  7. cla, clf, close

1. 绘制函数图

以下是最基本的绘图函数,这里以正弦曲线为例

1.1 颜色

颜色之间的对应关系为:

b---blue   c---cyan(青色)  g---green    k----black
m---magenta(洋红) r---red  w---white    y----yellow

1.2 线型

-      实线
--     短线
-.     短点相间线
:     虚点线

1.3 标记

标记风格有多种:

.  Point marker
,  Pixel marker
o  Circle marker
v  Triangle down marker 
^  Triangle up marker 
<  Triangle left marker 
>  Triangle right marker 
1  Tripod down marker
2  Tripod up marker
3  Tripod left marker
4  Tripod right marker
s  Square marker
p  Pentagon marker
*  Star marker
h  Hexagon marker
H  Rotated hexagon 
D Diamond marker
d  Thin diamond marker
| Vertical line (vlinesymbol) marker
_  Horizontal line (hline symbol) marker
+  Plus marker
x  Cross (x) marker
In [1]:
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0,np.pi*2, np.pi*2/10)
y = np.sin(x)

fig, ax = plt.subplots()
ax.plot(x,y,ls='dotted',color='r',lw=1.5,marker='>',markerfacecolor='None',markersize=15)
# markerfacecolor 可以设置marker的填充颜色,None为不填充
plt.show() 
# 在 jupyter notebook 中有两种显示图片的方式:fig 或 plt.show(),两者效果相同
# 在 terminal 中 对应两种为 fig.show() 和 plt.show()
# 在 terminal 中 fig.show() 不会中止程序,而 plt.show() 会中止程序,直到你关闭图像窗口才继续运行
In [2]:
# 颜色、标记、连线 可以简化成一个字符串,例如:'go-.'
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0,np.pi*2, np.pi*2/10)
y = np.cos(x)

fig, ax = plt.subplots()
ax.plot(x,y,'go-.',lw=1.5,markerfacecolor='None',markersize=15)

plt.show()

1.4 图例

In [3]:
import numpy as np
import matplotlib.pyplot as plt

# Make some fake data.
a = b = np.arange(0, 3, .02)
c = np.exp(a)
d = c[::-1]

# Create plots with pre-defined labels.
fig, ax = plt.subplots()
ax.plot(a, c, 'k--', label='Model length')
ax.plot(a, d, 'k:', label='Data length')
ax.plot(a, c + d, 'k', label='Total message length')

legend = ax.legend(loc='best', shadow=True, fontsize='x-large')
# loc: best
# upper left | upper center | upper right
# lower left |lower center | lower right
# center left | center | center right

# Put a nicer background color on the legend.
# legend.get_frame().set_facecolor('#00FFCC')
legend.get_frame().set_facecolor('cyan')

plt.show()

2. 坐标轴设置

</2>

In [4]:
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

ax.set_xlim([0,20]) # 坐标轴范围
ax.set_ylim([0,10])
ax.set_aspect('equal') # 坐标比例 也可以是 'auto'
# ax.set_aspect(2) # 纵坐标比横坐标
ax.set_xticks(range(0,21,2)) # 设置刻度
ax.set_yticks(range(11))
ax.grid() # 绘制网格
plt.show()

3. 文字设置

In [5]:
import matplotlib.pyplot as plt

fig = plt.figure()
fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')

ax = fig.add_subplot(111)
fig.subplots_adjust(top=0.85) # 控制子图占画布的比例,在 notebook 中运行不明显
# 例如:fig.subplots_adjust(left=0.08, bottom=0.35, right=0.97, top=0.75, wspace=0.25, hspace=0.25)
# 表示:子图左侧到画布的 0.08,底部到画布的 0.35 的位置,右侧到画布的 0.97,顶部到画布的 0.75,横向子图距离0.25,纵向子图距离0.25
ax.set_title('axes title') # 子图的名称

ax.set_xlabel('xlabel', fontsize=15, color='green') # 坐标轴的名称
ax.set_ylabel('ylabel')

ax.text(3, 8, 'boxed italics text in data coords', style='italic',
        bbox={'facecolor':'red', 'alpha':0.5, 'pad':10})

ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15) # 纯字符串,里面的反斜杠不代表转义

ax.text(3, 2, u'unicode: Institut f\374r Festk\366rperphysik') # unicode 

ax.text(0.95, 0.01, 'colored text in axes coords',
        verticalalignment='bottom', horizontalalignment='right',
        transform=ax.transAxes,
        color='green', fontsize=15)


ax.plot([2], [1], 'o')
ax.annotate('annotate', xy=(2, 1), xytext=(3, 4),
            arrowprops=dict(facecolor='black', shrink=0.05))

ax.axis([0, 10, 0, 10])
ax.set_xticks(range(11))

plt.show()

4. 绘制多幅子图

4.1 subplots

这种方法比较简洁,同时很规范。即使不绘制多幅子图,也建议采用这种方式。

In [6]:
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2,0.005)
y = np.exp(x)

fig, axs = plt.subplots(2,3,figsize=(15,10),dpi=90) 
# 2 行 3 列,前两个参数缺省时代表没有子图
# figsize 单位是英寸,参数顺序为:宽、高 如果想生成特定像素的图片,则需要设定 dpi(dots per inch),通常 100 左右就很清晰了
# axs.shape: (2,3)
for i in range(6):
    axs[i/3,i%3].plot(x, np.sin((i+1)*10*x)*y)
plt.show()

4.2 add_subplot

这种方法步骤最清晰,可以看到是先建立 figure 实例,再逐一添加 axis 实例。

In [7]:
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2,0.005)
y = np.exp(x)

fig = plt.figure(figsize=(15,10),dpi=90)
for i in range(6):
    ax = fig.add_subplot(2,3,i+1)
    ax.plot(x, np.sin((i+1)*10*x)*y)
fig
Out[7]:

4.3 subplot

这种方法最不规范,完全体现不出建立 figure 和 axis 实例的过程,但是最简洁。PS,没有找到这种方法如何设置画布参数。

In [8]:
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2,0.005)
y = np.exp(x)

for i in range(6):
    plt.subplot(2,3,i+1)
    plt.plot(x, np.sin((i+1)*10*x)*y)
    
plt.show()

5. 特殊形状

5.1 椭圆

In [9]:
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

#fig = plt.figure()
#ax = fig.add_subplot(111)
fig, ax = plt.subplots()
ellipse = Ellipse(xy=(10,5),width=20,height=10,angle=30,edgecolor='r',fc='green',lw=2, ls='dashed') 
# angle 是椭圆逆时针旋转的角度 单位是度
# fc facecolor,设置成 None 表示没有颜色,也可以设置 fill=False
# ls 或 linestyle:
# [‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | '-' | '--' | '-.' | ':']
ax.add_patch(ellipse)
ax.set_aspect('equal')
#ax.autoscale()
ax.set_ylim([0,10])
ax.set_xlim([0,20])
#fig.tight_layout()
ax.set_xticks(range(0,21))
ax.set_yticks(range(0,11))
#plt.xticks(range(0,21)) # 考虑到多个子图的情况,尽量不通过 plt 设置图形特征
#plt.yticks(range(0,11))
plt.grid()
plt.draw()
plt.show()

5.2 矩形

In [10]:
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

fig, ax = plt.subplots()
rect = Rectangle((2,1),3,4, edgecolor='g', fc='None', lw=2)
# 参数依次是 左下角坐标,宽度,高度
ax.add_patch(rect)
ax.set_aspect('equal')
ax.set_xlim([0,10])
ax.set_xticks(range(11))
ax.set_ylim([0,10])
ax.set_yticks(range(11))
ax.grid()
plt.draw()
plt.show()
In [ ]: