6.8 繪圖例項與總結
阿新 • • 發佈:2019-01-24
6.8.1 繪圖例項
從網路上下載真實資料CSV檔案,本資料集彙總了從1970年到2011年之間美國大學各專業中女生數佔總學生數的百分比例數值,如下圖所示:
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()
顯示結果:
圖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()
顯示結果:
圖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()
顯示結果:
圖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()
顯示結果:
圖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()
顯示結果:
圖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()
顯示結果:
常規圖
散點圖(Scatter Plots)
示例程式碼:
n = 1024
X = np.random.normal(0,1,n)
Y = np.random.normal(0,1,n)
plt.scatter(X,Y)
plt.show()
顯示結果:
散點圖
柱狀圖(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()
顯示結果:
柱狀圖
等高線圖(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()
顯示結果:
等高線圖
顯示影象(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()
顯示結果:
顯示影象
餅圖(Pie Plots)
示例程式碼:
Z = np.random.uniform(0, 1, 20)
plt.pie(Z)
plt.show()
顯示結果:
餅圖
向量場圖(Quiver Plots)
示例程式碼:
n = 8
X, Y = np.mgrid[0:n, 0:n]
plt.quiver(X, Y)
顯示結果:
向量場圖
網格線(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()
顯示結果:
三維圖