1.绘图最基础的代码
import matplotlib.pyplot as pltplt.plot(data)
2.figure和subplot
figure
是一个图形对象,它代表整个图形窗口或画布。subplot
是用来在一个figure
中创建多个子图的工具。通过subplot
,你可以把一个大的画布分成多个区域,每个区域显示不同的图。
In [16]: fig = plt.figure()In [17]: ax1 = fig.add_subplot(2, 2, 1)
In [18]: ax2 = fig.add_subplot(2, 2, 2)
In [19]: ax3 = fig.add_subplot(2, 2, 3)In [21]: ax1.hist(np.random.randn(100), bins=20, color='k', alpha=0.3)
In [22]: ax2.scatter(np.arange(30), np.arange(30) + 3 * np.random.randn(30))
In [23]: ax3.plot(np.random.randn(50).cumsum(), 'k--')
hist
是 matplotlib
用来绘制 直方图 的函数。scatter
用于绘制 散点图。
还有一种分画布和子图的常见代码:
import matplotlib.pyplot as plt# 创建 2 行 1 列的子图
fig, axes = plt.subplots(2, 1)# 在第一个子图(axes[0])上绘图
axes[0].plot([1, 2, 3], [1, 4, 9])
axes[0].set_title('Plot 1')# 在第二个子图(axes[1])上绘图
axes[1].plot([1, 2, 3], [1, 2, 3])
axes[1].set_title('Plot 2')# 显示图形
plt.tight_layout() # 自动调整布局,避免标题和图形重叠
plt.show()
顺带提一嘴,matplotlib就在最后一个用过的subplot(如果没有则创建一个)上进行绘制,比如这里在第三个subplot上作图:
fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)In [20]: plt.plot(np.random.randn(50).cumsum(), 'k--')
所以,我们要做一幅图,最好把所有作图的步骤放在一个In输入单元格里。
3.颜色、标记和线型
上下两行代码的作用相同,上面是下面的简化版,color是颜色,linestyle是线型,marker是标记。
plt.plot(randn(30).cumsum(), 'ko--')plt.plot(randn(30).cumsum(), color='k', linestyle='dashed', marker='o')
4.设置标题、轴标签、刻度以及刻度标签
ax.set_xticks([0, 250, 500, 750, 1000])ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'], rotation=30, fontsize='small')ax.set_title('My first matplotlib plot')ax.set_xlabel('Stages')
5.一张图里多条线以及图例
在一张图可以画多条线就像下面那样,每条线设置个标签,最后用legend创建图例,loc='best'表示在最佳位置创建。
from numpy.random import randn
plt.plot(randn(1000).cumsum(), 'k',label='one')
plt.plot(randn(1000).cumsum(), 'k--',label='two')
plt.plot(randn(1000).cumsum(), 'k.',label='three')
plt.legend(loc='best')
6.将图表保存到文件
使用savefig保存图片,一般用.png格式,在发布图片时最常用到两个重要的选项是dpi(控制“每英寸点数”分辨率)和bbox_inches(可以剪除当前图表周围的空白部分)。要得到一张带有最小白边且分辨率为400DPI的PNG图片,操作如下:
plt.savefig('figpath.png', dpi=400, bbox_inches='tight')
像刚才提到的,这行代码要和之前的绘图代码放到同一个In输入,防止出错。
7.Series和DataFrame绘图
使用pandas绘图与之前主要区别在于,之前是在图里面绘制(ax.plot()),或者直接绘制(plt.plot()),这里是在Series或DataFrame后接上plot()。
In [60]: s = pd.Series(np.random.randn(10).cumsum(), index=np.arange(0, 100, 10))
In [61]: s.plot()
DataFrame的plot方法会在一个subplot中为各列绘制一条线,并自动创建图例。
In [62]: df = pd.DataFrame(np.random.randn(10, 4).cumsum(0),....: columns=['A', 'B', 'C', 'D'],....: index=np.arange(0, 100, 10))
In [63]: df.plot()
8.使用Series和DataFrame绘制柱形图等
主要语句是类似于series或DataFrame后面接上plot再接上相应关键字,这里以柱状图为例:
In [64]: fig, axes = plt.subplots(2, 1)
In [65]: data = pd.Series(np.random.rand(16), index=list('abcdefghijklmnop'))
In [66]: data.plot.bar(ax=axes[0], color='k', alpha=0.7)
In [67]: data.plot.barh(ax=axes[1], color='k', alpha=0.7)
plot.bar()和plot.barh()分别绘制水平和垂直的柱状图。
对于DataFrame,柱状图会将每一行的值分为一组,并排显示。
In [69]: df = pd.DataFrame(np.random.rand(6, 4),....: index=['one', 'two', 'three', 'four', 'five', 'six'],....: columns=pd.Index(['A', 'B', 'C', 'D'], name='Genus'))
In [70]: df
Out[70]:
Genus A B C D
one 0.370670 0.602792 0.229159 0.486744
two 0.420082 0.571653 0.049024 0.880592
three 0.814568 0.277160 0.880316 0.431326
four 0.374020 0.899420 0.460304 0.100843
five 0.433270 0.125107 0.494675 0.961825
six 0.601648 0.478576 0.205690 0.560547
In [71]: df.plot.bar()
对于在绘制一个图形之前,需要进行合计的数据,使用seaborn可以减少工作量。seaborn的相应内容比较复杂,记不了那么多,只能用的时候再看了。