目录
坐标轴设计
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-1,1,50)
y1=2*x+1
y2=x**2
#设置图标属性,若不添加则默认是顺序排列
plt.figure()
'''plt.figure(
num=None,
figsize=None,
dpi=None,
facecolor=None,
edgecolor=None,
frameon=True,
FigureClass=<class 'matplotlib.figure.Figure'>,
clear=False,
**kwargs,
)'''
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
#坐标轴设计
plt.xlim((-1,2))#xlim((left, right))
plt.ylim((-2,3))#ylim((bottom, top))
plt.xlabel('x')#坐标轴标记
plt.ylabel('y')
#坐标轴ticks角标设计
new_ticks=np.linspace(-1,2,5)
print(new_ticks)
plt.xticks(new_ticks)# plt.xticks(ticks=None, labels=None, **kwargs)
plt.yticks([-2,-1,0,1,2],[r'$reall\ bad$',r'$bad$',r'$normal$',r'$good$',r'$really\ good$'])#一一对应关系
#gca='get current axis'
ax=plt.gca()
#获得坐标轴的度量
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')#设置下面的轴为x轴
ax.yaxis.set_ticks_position('left')#设置左面的轴为y轴
ax.spines['bottom'].set_position(('data',0))#将x轴放在y=0处
ax.spines['left'].set_position(('data',1))#将y轴放在x=1处
Lengend图例
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-1,1,50)
y1=2*x+1
y2=x**2
#设置图标属性,若不添加则默认是顺序排列
plt.figure()
#坐标轴设计
plt.xlim((-1,2))#xlim((left, right))
plt.ylim((-2,3))#ylim((bottom, top))
plt.xlabel('x')#坐标轴标记
plt.ylabel('y')
#坐标轴ticks角标设计
new_ticks=np.linspace(-1,2,5)
print(new_ticks)
plt.xticks(new_ticks)# plt.xticks(ticks=None, labels=None, **kwargs)
plt.yticks([-2,-1,0,1,2],[r'$reall\ bad$',r'$bad$',r'$normal$',r'$good$',r'$really\ good$'])#一一对应关系
# plt.plot(x,y2,label='up')
# plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--',label='down')
# plt.legend()使用默认参数生成图例
l1,=plt.plot(x,y2,label='up')#注意使用handles生成图例时 形式为 l1,=plt.plot()
l2,=plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--',label='down')
plt.legend(handles=[l1,l2],labels=[1,2],loc='best')
标注
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-3,3,50)
y=2*x+1
plt.figure(num=1,figsize=(8,5))
plt.plot(x,y)
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))
#为某一点添加注释
x0=1
y0=2*x0+1
plt.scatter(x0,y0,s=50,c='b')
plt.plot([x0,x0],[0,y0],'k--',lw=2)
#方法一
plt.annotate(r'$2x+1=%s$'% y0,xy=(x0,y0),xycoords='data',xytext=(+30,-30),textcoords='offset points',arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2'))
#方法二
plt.text(-2,2,r'$a$')
tick能见度
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-3,3,50)
y=0.1*x
plt.figure()
plt.plot(x,y,'b',linewidth=10)
plt.ylim(-2,2)
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))
for labels in ax.get_xticklabels()+ax.get_yticklabels():
labels.set_fontsize(12)
labels.set_bbox(dict(facecolor='black',edgecolor='None',alpha=0.1))
Scatter散点图
import matplotlib.pyplot as plt
import numpy as np
n=1024
x=np.random.normal(0,1,n)
y=np.random.normal(0,1,n)
t=np.arctan2(y,x)
plt.scatter(x,y,s=75,c=t,alpha=0.5)
plt.xlim((-1.5,1.5))
plt.ylim((-1.5,1.5))
plt.xticks(())
plt.yticks(())
Bar柱状图
import matplotlib.pyplot as plt
import numpy as np
n=12
X=np.arange(n)
Y1=(1-X/float(n))*np.random.uniform(0.5,1.0,n)
Y2=(1-X/float(n))*np.random.uniform(0.5,1.0,n)
#facecolor柱状图的颜色,edgecolor边框的颜色
plt.bar(X,+Y1,facecolor='#9999ff',edgecolor='white')
plt.bar(X,-Y1,facecolor='#ff9999',edgecolor='white')
for x,y in zip(X,Y1):
#ha水平对齐方式,va垂直对齐方式
plt.text(x+0.4,y+0.5,'%.2f'%y,ha='center',va='bottom')
for x,y in zip(X,Y2):
plt.text(x+0.4,-y-0.5,'-%.2f'%y,ha='center',va='bottom')
plt.xlim(-5,n)
plt.xticks(())
plt.ylim((-1.25,1.25))
plt.yticks(())
contours等高线图
import matplotlib.pyplot as plt
import numpy as np
def f(x,y):
#计算高度公式
return(1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n=256
x=np.linspace(-3,3,n)
y=np.linspace(-3,3,n)
#变换成网格
X,Y=np.meshgrid(x,y)
#为等高图填充颜色
plt.contourf(X,Y,f(X,Y),8,alpha=0.5,cmap=plt.cm.hot)
#等高线的线
C=plt.contour(X,Y,f(X,Y),8,color='b',linewidth=.5)
#为等高线添加label
plt.clabel(C,inline=True,fontsize=10)
plt.xticks(())
plt.yticks(())
显示图片
import matplotlib.pyplot as plt
import numpy as np
# image data
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
0.365348418405, 0.439599930621, 0.525083754405,
0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)
plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')
plt.colorbar(shrink=.92)
plt.xticks(())
plt.yticks(())
plt.show()
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)
# height value
Z = np.sin(R)
#rstride表示行步长,cstride表示列步长
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
#绘制热力图
#zdir表示从哪个方向投影,offset表示表示生成的热力图放在哪里
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.get_cmap('rainbow'))
ax.set_zlim(-2, 2)
plt.show()
Subplot分格显示
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# method 1: subplot2grid
plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3) # stands for axes
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))
ax4.scatter([1, 2], [2, 2])
ax4.set_xlabel('ax4_x')
ax4.set_ylabel('ax4_y')
ax5 = plt.subplot2grid((3, 3), (2, 1))
# method 2: gridspec
plt.figure()
gs = gridspec.GridSpec(3, 3)
# use index from 0
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])
# method 3: easy to define structure
#sharex共享x轴,sharey共享y轴
f, ((ax11, ax12), (ax13, ax14)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax11.scatter([1,2], [1,2])
plt.tight_layout()
plt.show()
图中图
import matplotlib.pyplot as plt
fig = plt.figure()
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
# below are all percentage
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
ax1 = fig.add_axes([left, bottom, width, height]) # main axes
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')
ax2 = fig.add_axes([0.2, 0.6, 0.25, 0.25]) # inside axes
ax2.plot(y, x, 'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')
# different method to add axes
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')
次坐标
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 *y1
fig, ax1 = plt.subplots()
ax2 = ax1.twinx() # mirror the ax1
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')
plt.show()