# Matplotlib 繪圖技巧:加上資料標籤及改變字型 > 作者:王一哲 > 日期:2023年5月11日 ## 加上資料標籤 在某些特殊的狀況下,會在數據點旁邊標示資料點的數值。下方程式碼第14 ~ 16行,依序讀取串列 x、y 的元素,組合成字串 txt,再用 annotate \[[1](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.annotate.html)\] 將 txt 標示在數據點的右側,下圖是採用預設字型的效果。 ```python= import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [3, 5, 7, 9, 11] plt.figure(figsize=(8, 6), dpi=96) plt.xlabel("x", fontsize=24) plt.ylabel("y", fontsize=24) plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.grid(color="grey", linestyle="--", linewidth=1) plt.plot(x, y, marker="o", markerfacecolor="blue", markersize=8, linestyle="") for i in range(len(x)): txt = "(" + str(x[i]) + ", " + str(y[i]) + ")" plt.annotate(txt, (x[i]+0.1, y[i]-0.1), fontsize=18) plt.show() ``` <br /> <img height="80%" width="80%" src="https://imgur.com/dtefFld.png" style="display: block; margin-left: auto; margin-right: auto;"/> <div style="text-align:center">預設樣式</div> <br /><br /> ## 改變字型 由於我們經常使用的英文、數字字型為 Times New Roman,如果要將圖中的字型改為 Times New Roman,在第2行加上這行程式碼。 ```python plt.rcParams["font.family"] = "Times New Roman" ``` 使用 matplotlib.rc \[[2](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.rc.html)\] 也有同樣的效果。 ```python from matplotlib import rc rc("font", **{"family" : "Times New Roman"}) ``` <br /> <img height="80%" width="80%" src="https://imgur.com/Lh0Wb9A.png" style="display: block; margin-left: auto; margin-right: auto;"/> <div style="text-align:center">改變字型為 Times New Roman</div> <br /><br /> ## 將縱軸、横軸標籤為斜體 但通常物理量的代號為斜體字,單位則採用一般的字體,也就是在縱軸、横軸標籤內,只有部分字體是斜體字,為了達成這個效果,要將這2行程式碼改掉 ```python plt.xlabel("x", fontsize=24) plt.ylabel("y", fontsize=24) ``` 改成以下這樣 ```python plt.xlabel(r"$\mathit{x}$", fontsize=24) plt.ylabel(r"$\mathit{y}$", fontsize=24) ``` <br /> 下圖是修改後的成果,但是斜體字的字型不是 Times New Roman,也不是常用的數學式子字型。 <img height="80%" width="80%" src="https://imgur.com/bFcIi3s.png" style="display: block; margin-left: auto; margin-right: auto;"/> <div style="text-align:center">改變字型為 Times New Roman 但縱軸、横軸標籤為斜體</div> <br /><br /> ## 使用 $\LaTeX$ 功能 如果想要使用常見的數學式子字型,我認為效果最好的作法是使用 $\LaTeX$ 功能,在 **from matplotlib import rc** 這行之後加上,但是執行時要等幾秒鐘才會出現繪圖成果。 ```python rc("text", usetex=True) ``` <br /> <img height="80%" width="80%" src="https://imgur.com/cADdtOF.png" style="display: block; margin-left: auto; margin-right: auto;"/> <div style="text-align:center">使用 LaTeX 功能的效果</div> <br /><br /> ## 參考資料 1. [matplotlib.pyplot.annotate 官方說明書](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.annotate.html) 2. [matplotlib.pyplot.rc 官方說明書](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.rc.html) --- ###### tags:`Python`