前面两篇文章分别讲了 python 数据分析的模块安装和数据结构,本篇主要讲如何利用 Python 进行简单的绘图。绘图的主要模块是 Matplotlib,其优势如下:
画图质量高 方便快捷地绘制模块 绘图API ―― pyplot 模块 集成库 ―― pylab 模块(包含 NumPy 和 pyplot 中的常用函数) 一、基本绘图 import numpy as np import matplotlib.pyplot as plt N = 5 men_means = (20, 35, 30, 35, 27) index = np.arange(N) plt.plot(index, men_means) #index 为 X 轴,men_means 为 Y 轴 plt.savefig('plot.png') #保存图片 plt.show() #展示图片绘图结果:

二、修改图片属性 import numpy as np import matplotlib.pyplot as plt N = 5 men_means = (20, 35, 30, 35, 27) index = np.arange(N) #通过 color、linestyle、marker 等设置颜色、线条、点等属性 line = plt.plot(index, men_means, color='#AE81FF', linestyle='dashed', marker='o', label='men_means') #设置图例 plt.legend(loc='upper center', title='legend title') plt.title('this is title') plt.savefig('plot.png') plt.show()
绘图结果:

三、多图共存
在 excel 作图时,不同类型的图共存时会略微有些麻烦,并且最多两种不同类型的图同时存在,但是用 Python 作这种组合图时会方便很多,直接叠加即可。
import numpy as np import matplotlib.pyplot as plt N = 5 men_means = (20, 35, 30, 35, 27) women_means = (20, 10, 40, 30, 15) index = np.arange(N) x = np.arange(0, 5, 0.1) y = np.sin(x * np.pi) plt.plot(index, men_means) #折线图 plt.bar(index, women_means, color='red') #柱状图 plt.plot(x, y) # 三角函数 plt.savefig('plot.png') plt.show()绘图结果:

四、子图
上面的例子中,我们也可以通过一张图中的三个部分分别来展示三种图,这个时候我们需要用到 subplot 。
import numpy as np import matplotlib.pyplot as plt N = 5 men_means = (20, 35, 30, 35, 27) women_means = (20, 10, 40, 30, 15) index = np.arange(N) x = np.arange(0, 5, 0.1) y = np.sin(x * np.pi) fig, (ax1, ax2, ax3) = plt.subplots(3, 1) # (3, 1)代表将一张图分成三个部分 ax1.plot(index, men_means) ax2.bar(index, women_means) ax3.plot(x, y) plt.savefig('plot.png') plt.show()绘图结果:

除了这两种需求, excel 还有在一张图中添加不同刻度的功能,这里依然可以很方便地实现。
import numpy as np import matplotlib.pyplot as plt N = 5 men_means = (20, 35, 30, 35, 27) women_means = (20, 10, 40, 30, 15) index = np.arange(N) x = np.arange(0, 5, 0.1) y = np.sin(x * np.pi) fig, ax1 = plt.subplots() ax2 = ax1.twinx() #共用 X 轴,但 Y 轴是独立的 ax1.plot(index, men_means) ax1.bar(index, women_means, color='red') ax2.plot(x, y, color='green') plt.savefig('plot.png') plt.show()绘图结果如下:

五、动画
对 Matplotlib,不仅可以绘图,还可以制作动画效果,尝试一个官方的例子:
import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import matplotlib.animation as manimation FFMpegWriter = manimation.writers['ffmpeg'] metadata = dict(title='Movie Test', artist='Matplotlib', comment='Movie support!') writer = FFMpegWriter(fps=15, metadata=metadata) fig = plt.figure() l, = plt.plot([], [], 'k-o') plt.xlim(-5, 5) plt.ylim(-5, 5) x0, y0 = 0, 0 with writer.saving(fig, "writer_test.mp4", 100): for i in range(100): x0 += 0.1 * np.random.randn() y0 += 0.1 * np.random.randn() l.set_data(x0, y0) writer.grab_frame()