基本用法
1.1引入库文件
import matplotlib.pyplot as plt
1.2画直线
plt.plot(x,y)
plt.show
plt.plot(x,y1,color='red',linewidth = 10.0,linestyle = '--')
1.3画散点图
plt.scatter((1,2),(2,3))
标)
plt.scatter(X, Y, s=25, c=A, alpha=.5)
plt.show
1.4画柱状图
plt.bar((1,2),(2,3))
plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')
for x, y in zip(X, Y1):
plt.text(x + 0.1, y + 0.05, '%.2f' % y, ha='center', va='bottom')
plt.show
1.5等高线图
plt.contourf(X, Y, Z, 8, alpha=.75, cmap=plt.cm.cool)
C = plt.contour(X, Y, Z, 8, colors='black', linewidths=.5)
plt.clabel(C, inline=True, fontsize=10)
1.6显示图片
plt.imshow(a, interpolation='nearest', cmap='hot', origin='lower')
plt.colorbar(shrink=.92)
1.7显示3D图
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.get_cmap('rainbow'))
1.8显示动态图
from matplotlib import pyplot as plt
from matplotlib import animation
ani = animation.FuncAnimation(fig=fig,
func=animate,
frames=100,
init_func=init,
interval=20,
blit=True)
'''
fig 进行动画绘制的figure
func 自定义动画函数,即传入刚定义的函数animate
frames 动画长度,一次循环包含的帧数
init_func 自定义开始帧,即传入刚定义的函数init
interval 更新频率,以ms计
blit 选择更新所有点,还是仅更新产生变化的点。应选择True,但mac用户请选择False,否则无法显示动画
'''
动态图例子
from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x + i/10.0))
return line,
def init():
line.set_ydata(np.sin(x))
return line,
ani = animation.FuncAnimation(fig=fig,
func=animate,
frames=100,
init_func=init,
interval=20,
blit=True)
plt.show()
图框设置
2.1新的图框,图框设置编号、图框宽高(不改变刻度)
plt.figure()
plt.figure(num=3,figsize=(2,10))
2.2设置x、y轴刻度范围 x、y轴标注
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('I am x')
plt.ylabel('I am y')
2.3x、y轴重新规定刻度
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks(new_ticks)
plt.show
2.4使用文字代替原先的坐标轴
plt.yticks([-2, -1.8, -1, 1.22, 3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
plt.show()
2.5设置边框隐藏
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.spines['left'].set_color('none')
plt.show()
2.6设置坐标隐藏
plt.xticks(())
plt.yticks(())
2.7设置坐标轴在图片位置(绝对)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.show()
2.8设置坐标轴在图片位置(相对)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('axes', .5))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('axes',.5))
2.9线置于哪层
plt.plot(x, y, zorder=1)
2.10刻度能见度设置
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12)
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7, zorder=2))
2.11 次坐标轴
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
注释和线名称标注
3.1线名称标注
plt.plot(x, y1, label='linear line')
plt.plot(x, y2, label='square line')
plt.legend(loc='best')
3.2线名称标注替代
l1, = plt.plot(x, y1)
l2, = plt.plot(x, y2)
plt.legend(handles=[l1, l2], labels=['up', 'down'], loc='best')
3.3对一点注释
plt.annotate(r'$hello$' , xy=(x0, y0), xycoords='data', xytext=(+30, -30), textcoords='offset points',
fontsize=16,arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))
3.4文字注释
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
fontdict={'size': 16, 'color': 'r'})
图片排布设置
4.1多条线一张图、一条线一张图
plt.figure()
plt.plot(x,y1)
plt.figure()
plt.plot(x,y2)
plt.figure()
plt.plot(x,y2)
plt.plot(x,y1)
4.2一张大图画多张小图
plt.figure()
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])
plt.subplot(2,3,4)
plt.plot([0,1],[0,2])
plt.subplot(2,3,5)
plt.plot([0,1],[0,3])
plt.subplot(2,3,6)
plt.plot([0,1],[0,4])
plt.show()
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.figure()
gs = gridspec.GridSpec(3, 3)
ax6 = plt.subplot(gs[0, :])
ax7 = plt.subplot(gs[1, :2])
ax8 = plt.subplot(gs[1:, 2])
ax9 = plt.subplot(gs[-1, 0])
ax10 = plt.subplot(gs[-1, -2])
4.3共用x,y坐标轴
import matplotlib.pyplot as plt
f, ((ax11, ax12), (ax13, ax14)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax11.scatter([1,2], [1,2])
plt.tight_layout()
plt.show()
4.4图中图
import matplotlib.pyplot as plt
fig = plt.figure()
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(y, x, 'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')
plt.axes([0.6, 0.2, 0.25, 0.25])
plt.plot(y[::-1], x, 'g')
plt.xlabel('x')
plt.ylabel('y')
plt.title('title inside 2')