1. 程式人生 > >Matplotlib資料視覺化(3):文字與軸

Matplotlib資料視覺化(3):文字與軸

 

在一幅圖表中,文字、座標軸和影象的是資訊傳遞的核心,對著三者的設定是作圖這最為關心的內容,在上一篇部落格中雖然列舉了一些設定方法,但沒有進行深入介紹,本文以圍繞如何對文字和座標軸進行設定展開(對影象的設定在後續介紹到各種圖繪製時介紹)。

這裡所說的文字是指在使用matplotlib作圖過程中通過程式碼的方式往圖中新增的各種文字,包括figure標題、axes標題、座標軸標籤、座標軸刻度標籤、註釋、普通文字等。軸設定指的是對與座標軸相關的的元素的設定,例如顯示範圍、刻度、刻度標籤等。

In [1]:
from matplotlib import pyplot as plt
import numpy as np
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']  # 中文字型支援
 

1 標題¶

 

(1)figure標題與axes標題

In [2]:
x1 = np.linspace(0.0, 5.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
fig = plt.figure(figsize=(8, 3))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
fig.subplots_adjust(top=0.85)
fig.suptitle('figure標題')
ax1.set_title('ax1-標題')
ax2.set_title('ax2-標題')
plt.show()
   

(2)字型設定

In [3]:
from matplotlib.font_manager import FontProperties

x1 = np.linspace(0.0, 5.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
fig = plt.figure(figsize=(8, 3))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
fig.subplots_adjust(top=0.85)
fig.suptitle('figure標題', color='red', fontsize=20)
font = FontProperties()  # 字型類
font.set_family('serif')
font.set_name('SimHei')
font.set_style('italic')
ax1.set_title('ax1-標題',fontproperties=font)  # 傳遞字型類設定字型
ax2.set_title('ax2-標題', color='green')
plt.show()
   

(3)設定水平距離

In [4]:
x1 = np.linspace(0.0, 5.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
fig, axs = plt.subplots(3, 1, figsize=(5, 10))
fig.subplots_adjust(top=0.93)
fig.suptitle('figure標題', color='red', fontsize=20)
locs = ['left', 'center', 'right']
for ax, loc in zip(axs, locs):
    ax.plot(x1, y1)
    ax.set_title('axes標題 '+ loc, loc=loc, color='blue')
plt.show()
   

(4)設定垂直距離

In [5]:
x1 = np.linspace(0.0, 5.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
fig, ax = plt.subplots(figsize=(5, 3))
fig.subplots_adjust(top=0.8)
ax.plot(x1, y1)
ax.set_title('垂直距離測試圖-標題', pad=