綜述
在可視化中需要考慮的基本元素是:畫布!
單圖
t = np.arange(0., 5., 0.2)
"""
figure用來定義畫布的基本屬性
"""
plt.figure(1)
"""
畫折線圖的函數(x,y,line_shape);如果要在一張圖中畫多條線直接在後面排就行。
"""
plt.plot(t, t, 'r--',t, t**2, 'bs', t, t**3, 'g^')
plt.show()
line1,line2,line3 = plt.plot(t, t, ‘r–’,t, t2, ‘bs’, t, t3, ‘g^’)會返回一個line對象,可以通過這個對象設置每條線的具體屬性
一圖多子圖
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure("2subplot")
plt.subplot(2,1,1)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(2,1,2)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
- subplot(row,column,index)用來定義子圖的位置。subplot(2,1,1)等價於subplot(211)表示當前子圖畫在2行1列的第1個位置(即上方)*
多圖多子圖
plt.figure(1) # 編號爲1的figure
plt.subplot(211) # figure1中的第一個子圖
plt.plot([1, 2, 3])
plt.subplot(212) # figure1中的第二個子圖
plt.plot([4, 5, 6])
plt.figure(2) # figure2
plt.plot([4, 5, 6]) # 默認使用subplot(111),此時figure2爲當
plt.show()
圖像修飾
plt.title:圖片標題
plt.xlabel:橫座標標題
plt.ylabel:縱座標標題
plt.tick_params:座標軸字體大小
plt.xticks([],rotation=90):座標軸字體旋轉,**以及座標軸的刻度**
實際舉例
# 展示圖像
def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array, true_label[i], img[i]
plt.grid(False)
# 定義x軸的刻度,可以設置得到一個均勻的刻度。
# xticks(locs,[labels],**kwargs)->locs:定義刻度的範圍;labels:對應每個刻度的標籤;**Kargs:定義每個標籤的旋轉、顏色等
plt.xticks([])
plt.yticks([])
# 顯示圖像
plt.imshow(img, cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),
class_names[true_label]),
color=color)
# 展示預測結果
def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array, true_label[i]
plt.grid(False)
plt.xticks(range(10))
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
# 設置縱座標的範圍
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)
thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue')
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
plt.subplot(num_rows, 2*num_cols, 2*i+1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(num_rows, 2*num_cols, 2*i+2)
plot_value_array(i, predictions[i], test_labels)
# 自動調整填充整個區域
plt.tight_layout()
plt.show()