6.8.1 绘图实例
从网络上下载真实数据CSV文件,本数据集汇总了从1970年到2011年之间美国大学各专业中女生数占总学生数的百分比例数值,如下图所示:
![](http://upload-images.jianshu.io/upload_images/5013892-b35d2675bbfd3ea3.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
1970-2011各专业女生百分比例
利用Pandas库导入CSV文件,并快速绘制生物学专业女生比例随着年份变化的曲线图(plot方法),示例代码:
import pandas as pd
import matplotlib.pyplot as plt
women_degrees = pd.read_csv('percent-bachelors-degrees-women-usa.csv')
plt.plot(women_degrees['Year'], women_degrees['Biology'])
plt.show()
显示结果:
![](http://upload-images.jianshu.io/upload_images/5013892-6467be9bbe240b2e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
图6.8-1
在同一子图中,绘制两条曲线,分别显示男女生在生物学专业随着年份增加变化的差异,并且增加标题、标签以及颜色等细节元素,示例代码:
plt.plot(women_degrees['Year'], women_degrees['Biology'], c='blue', label='Women')
plt.plot(women_degrees['Year'], 100-women_degrees['Biology'], c='green', label='Men')
plt.legend(loc='upper right')
plt.title('Percentage of Biology Degrees Awarded By Gender')
plt.show()
显示结果:
![](http://upload-images.jianshu.io/upload_images/5013892-aeb85fc7a8518b7e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
图6.8-2
可以利用子图ax对象的tick_params属性,忽略x轴和y轴的刻度,示例代码:
fig, ax = plt.subplots()
ax.plot(women_degrees['Year'], women_degrees['Biology'], label='Women')
ax.plot(women_degrees['Year'], 100-women_degrees['Biology'], label='Men')
ax.tick_params(bottom="off", top="off", left="off", right="off")
ax.set_title('Percentage of Biology Degrees Awarded By Gender')
ax.legend(loc="upper right")
plt.show()
显示结果:
![](http://upload-images.jianshu.io/upload_images/5013892-7d5681ec8b5e09c4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
图6.8-3
利用子图中spine对象中的items属性,可以忽略绘图显示的边框,示例代码:
fig, ax = plt.subplots()
ax.plot(women_degrees['Year'], women_degrees['Biology'], c='blue', label='Women')
ax.plot(women_degrees['Year'], 100-women_degrees['Biology'], c='green', label='Men')
ax.tick_params(bottom="off", top="off", left="off", right="off")
for key,spine in ax.spines.items():
spine.set_visible(False)
ax.legend(loc='upper right')
plt.show()
显示结果:
![](http://upload-images.jianshu.io/upload_images/5013892-a2a50e63fbb2ef7d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
图6.8-4
绘制在同一画布中绘制4个子图,分别显示4个专业的男女生比例随年份变化的趋势,示例代码:
major_cats = ['Biology', 'Computer Science', 'Engineering', 'Math and Statistics']
fig = plt.figure(figsize=(12, 12))
for sp in range(0,4):
ax = fig.add_subplot(2,2,sp+1)
ax.plot(women_degrees['Year'], women_degrees[major_cats[sp]], c='blue', label='Women')
ax.plot(women_degrees['Year'], 100-women_degrees[major_cats[sp]], c='green', label='Men')
for key,spine in ax.spines.items():
spine.set_visible(False)
ax.set_xlim(1968, 2011)
ax.set_ylim(0,100)
ax.set_title(major_cats[sp])
ax.tick_params(bottom="off", top="off", left="off", right="off")
plt.legend(loc='upper right')
plt.show()
显示结果:
![](http://upload-images.jianshu.io/upload_images/5013892-d235755a529e4fd9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
图6.8-5
6.8.2 总结
本章节介绍了几种常用图形的绘制方法与绘制细节,以下示例除了绘制以上常用图形,也加入其它图形绘制的简单方法,具体细节可以查阅相关资料,这里不再赘述。
常规图(Regular Plots)
示例代码:
import numpy as np
import matplotlib.pyplot as plt
n = 256
X = np.linspace(-np.pi, np.pi, n, endpoint=True)
Y = np.sin(2 * X)
plt.plot(X, Y + 1, color='blue', alpha=1.00)
plt.plot(X, Y - 1, color='blue', alpha=1.00)
plt.show()
显示结果:
![](http://upload-images.jianshu.io/upload_images/5013892-ecad5ee544828c03.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
常规图
散点图(Scatter Plots)
示例代码:
n = 1024
X = np.random.normal(0,1,n)
Y = np.random.normal(0,1,n)
plt.scatter(X,Y)
plt.show()
显示结果:
![](http://upload-images.jianshu.io/upload_images/5013892-b9d57c3d9917d680.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
散点图
柱状图(Bar Plots)
示例代码:
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)
plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')
for x, y in zip(X, Y1):
plt.text(x + 0.4, y + 0.05, '%.2f ' % y, ha='center', va='bottom')
plt.ylim(-1.25, +1.25)
plt.show()
显示结果:
![](http://upload-images.jianshu.io/upload_images/5013892-412a777ac0e1136f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
柱状图
等高线图(Contour Plots)
示例代码:
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=.75, cmap='jet')
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)
plt.show()
显示结果:
![](http://upload-images.jianshu.io/upload_images/5013892-ed0747fc0c449a81.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
等高线图
显示图像(Imshow)
示例代码:
def f(x, y):
return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
n = 10
x = np.linspace(-3, 3, 4 * n)
y = np.linspace(-3, 3, 3 * n)
X, Y = np.meshgrid(x, y)
plt.imshow(f(X, Y))
plt.show()
显示结果:
![](http://upload-images.jianshu.io/upload_images/5013892-a2f453c1439a5441.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
显示图像
饼图(Pie Plots)
示例代码:
Z = np.random.uniform(0, 1, 20)
plt.pie(Z)
plt.show()
显示结果:
![](http://upload-images.jianshu.io/upload_images/5013892-4c0d93d749575a6f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
饼图
向量场图(Quiver Plots)
示例代码:
n = 8
X, Y = np.mgrid[0:n, 0:n]
plt.quiver(X, Y)
显示结果:
![](http://upload-images.jianshu.io/upload_images/5013892-df6c7d8891d643ea.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
向量场图
网格线(Grids)
示例代码:
axes = plt.gca()
axes.set_xlim(0, 4)
axes.set_ylim(0, 3)
axes.set_xticklabels([])
axes.set_yticklabels([])
多图(Multi Plots)
示例代码:
plt.subplot(2, 2, 1)
plt.subplot(2, 2, 3)
plt.subplot(2, 2, 4)
三维图(3D Plots)
示例代码:
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
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)
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot')
plt.show()
显示结果:
![](http://upload-images.jianshu.io/upload_images/5013892-765897a6eed8805b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
三维图