9.添加标注 (Annotations)
10.添加網格線(Grid Lines)
11.顯示中文字型
12.儲存圖形(saving Figures)
13.高品質矢量圖輸出
9.添加标注 (Annotations)
有時候我們對某點如3∗sin(3∗pi/4)的值特别感興趣。
import numpy as np
print(3 * np.sin(3 * np.pi / 4))
2.121320343559643
如果想在圖示上标出這一點,可以使用annotate函數執行此操作。
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-2 * np.pi, 3 * np.pi, 70, endpoint=True)
F1 = np.sin(X)
F2 = 3 * np.sin(X)
ax = plt.gca()
plt.xticks( [-6.28, -3.14, 3.14, 6.28],
[r'$-2\pi$', r'$-\pi$', r'$+\pi$', r'$+2\pi$'])
plt.yticks([-3, -1, 0, +1, 3])
x = 3 * np.pi / 4
plt.scatter([x,],[3 * np.sin(x),], 50, color ='blue')
plt.annotate(r'$(3\sin(\frac{3\pi}{4}),\frac{3}{\sqrt{2}})$',
xy=(x, 3 * np.sin(x)),
xycoords='data',
xytext=(+20, +20),
textcoords='offset points',
fontsize=16,
arrowprops=dict(facecolor='blue'))
plt.plot(X, F1, label="$sin(x)$")
plt.plot(X, F2, label="$3 sin(x)$")
plt.legend(loc='lower left')
plt.show()
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIwczX0xiRGZkRGZ0Xy9GbvNGL2EzXlpXazxCMBRlT0cGRONzaq1Ee4cEZ2J1MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnL1EzMzEzMyITM4ADNwEjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
我們必須提供有關annotate參數的一些資訊。
參數 | 含義 |
---|---|
xy | coordinates of the arrow tip |
xytext | coordinates of the text location |
我們示例的xy和xytext位置在資料坐标中。 我們還可以選擇其他坐标系系統。 可以為xy和xytext的坐标系指定字元串值,指派給xycoords和textcoords。 預設值為“data”:
字元串值 | 坐标系統 |
---|---|
‘figure points’ | Points from the lower left of the figure |
‘figure pixels’ | Pixels from the lower left of the figure |
‘figure fraction’ | Fraction of figure from lower left |
‘axes points’ | Points from lower left corner of axes |
‘axes pixels’ | Pixels from lower left corner of axes |
‘axes fraction’ | Fraction of axes from lower left |
‘data’ | Use the coordinate system of the object being annotated (default) |
‘polar’ | (theta, r) if not native ‘data’ coordinates |
此外,還可以指定箭頭的屬性。 為此,我們必須為參數arrowprops提供一個箭頭屬性字典:
arrowprops key | 描述 |
---|---|
width | The width of the arrow in points |
headwidth | The width of the base of the arrow head in points |
headlength | The length of the arrow head in points |
shrink | Fraction of total length to shrink from both ends |
**kwargs | any key for matplotlib.patches.Polygon, e.g., facecolor |
在以下示例中,我們将更改上一示例的箭頭的外觀:
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-2 * np.pi, 3 * np.pi, 70, endpoint=True)
F1 = np.sin(X)
F2 = 3 * np.sin(X)
ax = plt.gca()
plt.xticks([-6.28, -3.14, 3.14, 6.28],
[r'$-2\pi$', r'$-\pi$', r'$+\pi$', r'$+2\pi$'])
plt.yticks([-3, -1, 0, +1, 3])
x = 3 * np.pi / 4
plt.scatter([x, ], [3 * np.sin(x), ], 50, color='blue')
plt.annotate(r'$(3\sin(\frac{3\pi}{4}),\frac{3}{\sqrt{2}})$',
xy=(x, 3 * np.sin(x)),
xycoords='data',
xytext=(+20, +20),
textcoords='offset points',
fontsize=16,
arrowprops=dict(facecolor='blue', headwidth=10, headlength=10, width=2, shrink=0.1))
plt.plot(X, F1, label="$sin(x)$")
plt.plot(X, F2, label="$3 sin(x)$")
plt.legend(loc='lower left')
plt.show()
10.添加網格線(Grid Lines)
import numpy as np
import matplotlib.pyplot as plt
def f(t):
return np.exp(-t) * np.cos(2 * np.pi * t)
def g(t):
return np.sin(t) * np.cos(1 / (t + 0.1))
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.plot(t1, g(t1), 'ro', t2, f(t2), 'k')
plt.grid(color='b', alpha=0.5, linestyle='dashed', linewidth=1.0)
plt.show()
11.顯示中文字型
Matplotlib預設是不支援顯示中文字元的。
解決方法: 可以使用 rc 配置(rcParams)來自定義圖形的各種預設屬性。
Windows作業系統支援的中文字型和代碼:
配置方式:
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']
示例如下:
import matplotlib.pyplot as plt
# 在jupyter notebook 中,設定下面兩行來顯示中文
plt.rcParams['font.family'] = ['sans-serif']
# 在 PyCharm 中,隻需要下面一行,‘STXingkai’:華文行楷
plt.rcParams['font.sans-serif'] = ['STXingkai']
days = list(range(1,9))
celsius_values = [25.6, 24.1, 26.7, 28.3, 27.5, 30.5, 32.8, 33.1]
plt.plot(days, celsius_values)
plt.xlabel('日期', size=16)
plt.ylabel('攝氏度', size=16)
plt.title('溫度變化', size=16)
plt.show()
另外的方法:
在每一處使用到中文輸出的地方,都加上一個字型屬性fontproperties
import matplotlib.pyplot as plt
days = list(range(1,9))
celsius_values = [25.6, 24.1, 26.7, 28.3, 27.5, 30.5, 32.8, 33.1]
plt.plot(days, celsius_values)
plt.xlabel('日期', fontproperties='SimHei', size=16)
plt.ylabel('攝氏度', fontproperties='STXingkai', size=16)
plt.title('溫度變化', fontproperties='SimHei', size=16)
plt.show()
12.儲存圖形(saving Figures)
savefig方法可用來儲存圖形到檔案中:
fig.savefig(“filename.png”)
可以指定分辨率DPI(Dots Per Inch,每英寸點數)和選擇輸出檔案格式:
可以采用PNG,JPG,EPS,SVG,PGF和PDF格式生成輸出。
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([0, 1, 2, 3, 4], [0, 3, 5, 9, 11])
plt.xlabel('Months')
plt.ylabel('Books Read')
plt.show()
fig.savefig('books_read.png')
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('books_read.png')
plt.imshow(img)
13.高品質矢量圖輸出
Jupyter Notebook中顯示svg矢量圖的設定: %config InlineBackend.figure_format = ‘svg’
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
import matplotlib.pyplot as plt
# 在jupyter notebook 中,設定下面兩行來顯示中文
plt.rcParams['font.family'] = ['sans-serif']
# 在 PyCharm 中,隻需要下面一行
plt.rcParams['font.sans-serif'] = ['SimHei']
days = list(range(1,9))
celsius_values = [25.6, 24.1, 26.7, 28.3, 27.5, 30.5, 32.8, 33.1]
fig = plt.figure()
plt.plot(days, celsius_values)
plt.xlabel('日期', size=16)
plt.ylabel('攝氏度', size=16)
plt.title('溫度變化', size=16)
plt.show()
fig.savefig('celsius_degrees.svg')