持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第22天,点击查看活动详情
1.matplotlib API入门
我们对matplotlib的引入约定是:
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
import numpy as np
data=np.arange(10)
plt.plot(data)
虽然seaborn这样的库和pandas的内置绘图函数能够处理许多普通的绘图任务, 但如果需要自定义一些高级功能的话就必须学习matplotlib API。
2.Figure和Subplot
matplotlib的图像都位于Figure对象中。 你可以用plt.figure创建一个新的Figure:
fig=plt.figure()
如果用的是IPython, 这时会弹出一个空窗口, 但在Jupyter中, 必须再输入更多命令才能看到。plt.figure有一些选项,特别是figsize,它用于确保当图片保存到磁盘时具有一定的大小和纵横比。不能通过空Figure绘图。 必须用add_subplot创建一个或多个subplot才行.
fig=plt.figure()
ax1=fig.add_subplot(2,2,1)
这条代码的意思是: 图像应该是2×2的(即最多4张图) , 且当前选中的是4个subplot中的第一个
(编号从1开始) 。 如果再把后面两个subplot也创建出来, 最终得到的图像如图9-2所示:
fig=plt.figure()
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
如果这时执行一条绘图命令(如plt.plot([1.5, 3.5, -2, 1.6])) , matplotlib就会在最后一个用过的
subplot(如果没有则创建一个) 上进行绘制, 隐藏创建figure和subplot的过程。 因此, 如果我们执
行下列命令:
plt.plot(np.random.randn(50).cumsum(),'k--')
fig=plt.figure()
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
plt.plot(np.random.randn(50).cumsum(),'k--')
"k--"是一个线型选项, 用于告诉matplotlib绘制黑色虚线图。 上面那些由fig.add_subplot所返回的对
象是AxesSubplot对象, 直接调用它们的实例方法就可以在其它空着的格子里面画图了
fig=plt.figure()
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
plt.plot(np.random.randn(50).cumsum(),'k--')
ax1.hist(np.random.randn(100),bins=20,color='k',alpha=0.3)
ax2.scatter(np.arange(30),np.arange(30)+3*np.random.randn(30))
fig,axes=plt.subplots(2,2,sharex=True,sharey=True)
for i in range(2):
for j in range(2):
axes[i,j].hist(np.random.randn(500),bins=50,color='k',alpha=0.5)
plt.subplots_adjust(wspace=0,hspace=0)
这里我们可以看出,其中轴标签重叠了,matplotlib不会检查标签是否重叠,所以对于这种情况,你只能自己设定刻度位置和刻度标签。
3.颜色、标记和线型
matplotlib的plot函数接受一组X和Y坐标, 还可以接受一个表示颜色和线型的字符串缩写。 例如:
from numpy.random import randn
plt.plot(randn(30).cumsum(),'ko--')