目錄
目錄
前言
今天我們來學習一下文本的顯示
(一)中文顯示
1.全局的設置
(1)說明:
在matplotlib目前的繪圖文字顯示時,是不支持中文的,我們想輸出中文,需要設置一下。
matplotlib.rcParams['屬性'] = '屬性值' ,可以修改全局字體
字體屬性 'font.family' | |
---|---|
黑體 | 'SimHei' |
楷體 | 'Kaiti' |
隸書 | 'LiSu' |
仿宋 | 'FangSong' |
幼圓 | 'YouYuan' |
華文宋體 | 'STSong' |
字體格式 'font.style' | |
正常 | 'normal' |
斜體 | 'italic' |
字體的大小'font.size' | |
字號 | |
大號 | large |
大小號 | x-small |
(2)源代碼
import matplotlib.pyplot as plt
import matplotlib
# 將全局的字體設置為黑體
matplotlib.rcParams['font.family'] = 'SimHei'
y = [3, 1, 4, 5, 2]
plt.plot(y)
plt.ylabel("縱軸的值")
plt.xlabel("橫軸的值")
# 自動保存圖片
plt.savefig("test", dpi=600)
plt.show()
(3)輸出效果
2.局部的設置
(1)說明:
為了不影響全局的字體,我們可以選擇在局部改變字體。
在需要輸入中文的地方,輸入一下參數
字體 | fontproperties="SimHei" |
---|---|
字號 | fontsize=20 |
顏色 | color="green" |
(2)源代碼
import matplotlib.pyplot as plt
y = [3, 1, 4, 5, 2]
plt.plot(y)
# 改變局部變量
plt.ylabel("縱軸的值", fontproperties="SimHei", fontsize=20)
plt.xlabel("橫軸的值", fontproperties="SimHei", fontsize=20, color="green")
plt.savefig("test", dpi=600)
plt.show()
(3)輸出效果
(二)文本顯示
(1)說明:
x軸標簽 | plt.xlabel("string") |
---|---|
y軸標簽 | plt.ylabel("string") |
整體的標簽 | plt.titile("string") |
任意的位置 | plt.text(x, y, "string") |
帶箭頭 | plt.annotate(s, xy=(x, y), xytext=(x, y),arrowprops) |
$$ | 數學公式 |
帶箭頭的參數:
s : "string"
xy: 箭頭的坐標
xytext: 文字的坐標
arrowprops: 箭頭的屬性,字典類型
arrowprops=dict(facecolor="red", shrink=0.1, width=2)
facecolor:箭頭顏色
shrink:箭頭的長度(兩坐標距離的比例,0~1)
width:箭頭的寬度
(2)源代碼
import matplotlib.pyplot as plt
y = [3, 1, 4, 5, 2]
plt.plot(y)
# x , y 軸標簽
plt.ylabel("縱軸的值", fontproperties="SimHei", fontsize=20)
plt.xlabel("橫軸的值", fontproperties="SimHei", fontsize=20, color="green")
# 整體的標簽
plt.title(r"整體的標簽 $x^{2y +3}$", fontproperties="SimHei", fontsize=30)
# 顯示網格
plt.grid(True)
# 再坐標為(1,3)處輸出文字
plt.text(1, 3, r"$\mu=100$")
# 有箭頭的文字
plt.annotate(r"$\sum_1^nx$", xy=(3, 3), xytext=(3, 4.5),
arrowprops=dict(facecolor="red", shrink=0.1, width=2))
# 設置坐標軸 x(0, 4) y(0, 6)
plt.axis([0, 4, 0, 6])
plt.show()