长时间没有再使用matplotlib,最近又拿出来简单看了一遍,不过在安装的时候发现安装完成后运行时出现的界面和以往的不一样。主要有以下不同:
- 在新版本pycharm中使用时,运行的plot会自动出现在ide的窗口里,不是很方便,如果不喜欢可以在file->settings->tools->Python Scientific->show plots in tool window 前面的勾选框不勾选即可。
- 最新版matplotlib,好像是2.2.几还是2.3,在使用时窗口发生了很大的变化,好多按钮不见了,所以我还是安装了2.0.0,pip install matplotlib==2 即可。
好,现在开始正式记录常用的一些函数,方便使用时查询。
import matplotlib.pyplot as plt
- 设置在坐标轴在最中间(其他位置同理)
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,100)
y = x
plt.plot(x,y)
plt.xlim(-3,3)
ax = plt.gca()
ax.spines['top'].set_color('None')
ax.spines['right'].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()
- 最基本的画线(平滑的曲线)
plt.plot(x_data,y_data) #可以只指定两个点,那就是简单的画直线
- 标题
plt.title('my title')
- 设置曲线的颜色和style
plt.plot(x,y,color='black',linewidth=2,linestyle='--')
- 显示初始时的x轴和y轴的上下限
plt.xlim((-3,3)) plt.ylim((-1,4))
- 设置x轴和y轴的标签
plt.xlabel('i am x') plt.ylabel('i am y')
- 设置x轴和y轴的坐标
new_ticks = np.linspace(-5,5,15)
plt.xticks(new_ticks)
plt.yticks([-2,-1,0,1,2],['too bad','bad','normal','good','really good'])
- 设置坐标轴不可见
ax = plt.gca()
ax.spines['top'].set_color('none')
- 设置坐标轴的位置
ax.spines['bottom'].set_position(('data',1)) # 下部轴显示在纵轴数据为1的地方(即下部轴为y=1直线)
- 设置图例(legend)
plt.plot(x,y1,label='first')
plt.plot(x,y2,label='second')
plt.legend() #默认就是loc=‘best’,会自动寻找较空的位置放图例
# plt.legend(loc='lower left / upper right / best')
- 设置注解(annotation)两种方式
plt.annotate('hello annotate',xy=(x0,y0),xycoords='data',xytext=(30,-30),textcoords = 'offset points',
fontsize=12,arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.5'))
plt.text(-1,-4,r'$this\ is\ text\ \alpha_2\ \sigma\ \mu$',
fontdict={'size':16,'color':'r'})
- 散点图
plt.scatter(x_data,y_data,marker=,color=,alpha=)
- 去掉ticks(坐标轴上数字等)
plt.xticks(())
柱状图
plt.bar(x,+y1,facecolor='red',edgecolor='white')
plt.bar(x,-y2,facecolor='blue',edgecolor='white') # -y2表示显示在横坐标下方
for x0,y0 in zip(x,y1):
plt.text(x0,y0+0.005,'%.2f'%y0,ha='center',va='bottom') # ha表示水平对齐
for x0,y0 in zip(x,y2):
plt.text(x0,-y0-0.005,'%.2f'%y0,ha='center',va='top')
- 等高线
X,Y = np.meshgrid(x,y)
plt.contourf(X,Y,Z,8,alpha=0.75,cmap=plt.cm.hot) #Z代表高度,8代表有9个分界线,cmap为颜色对应
C = plt.contour(X,Y,Z,8,linewidth=1,colors='black')
plt.clabel(C,inline=True,fontsize=10)
- 3D图
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-4,4,0.2)
Y = np.arange(-4,4,0.2)
X,Y = np.meshgrid(X,Y)
R = np.sqrt(X**2+Y**2)
Z = np.sin(R)
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=plt.cm.rainbow)
ax.contourf(X,Y,Z,zdir='z',offset=-2,cmap=plt.cm.rainbow)
- 子图
ax1 = plt.subplot2grid((3,3),(0,0),colspan=3,rowspan=1) # 总的分3行3列,从(0,0)开始
ax1.set_title('subplot 1') # 注意此时的设置都要使用set_xxx函数不能直接用title()
ax2 = plt.subplot2grid((3,3),(1,0),colspan=1,rowspan=1)
ax2.plot([0,1],[0,3])
只记录以上常用函数,更多函数使用可以查看莫烦python关于matplotlib的教程(bilibili是个学习网站)