用Python隨手畫個圖
- 2019 年 10 月 7 日
- 筆記
最近遇到個任務需要畫一些坐標圖,我就在想,用了這麼長時間的 Python 了,能不能用 Python 畫圖呢?學習一門語言不能只為了學習語言而學習,要做到學以致用。Google 了一下,果然有新的發現,Python 中 matplotlib 庫是專門用來畫圖的,操作了一番後,發現用 Python 畫圖真的爽,人生苦短,快用 Python!下面簡單的介紹一下 matplotlib 庫的用法,起到一個拋轉引玉的作用,更多好玩的事情等待著咱們一起來探索。
我有如下數據集,想要在坐標軸上畫出它們的影像:
x = [-1.0, -0.5, 1.5, 2.5, 4.0, 5.5, 7.0, 9.0, 10.5, 11.5, 13.0, 15.5, 18.0, 20.5, 23.0, 25.5, 28.0, 33.0, 38.0, 43.0] data1 = [0.1, 0.9, 5.6, 7.8, 14.8, 21.2, 26.3, 32.0, 36.6, 39.4, 42.6, 47.9, 52.2, 56.1, 59.8, 63.2, 66.3, 72.2, 77.5, 81.5] data2 = [0.1, 0.2, 2.1, 3.7, 6.8, 9.8, 11.8, 14.9, 16.1, 17.2, 18.6, 20.7, 22.6, 24.4, 26.0, 27.5, 28.9, 31.0, 32.9, 34.3]
讓我們一起來看下如何用 Python 中 matplotlib 庫畫出它們的影像吧。
想要用 matplotlib,首先你需要導入這個庫:
import matplotlib.pyplot as plt
然後輸入一下程式碼:
plt.title("curve") # 標題 plt.xlabel("x") # x 軸資訊 plt.ylabel("y") # y 軸資訊 plt.plot(x, data1) # 畫出影像 plt.plot(x, data2) plt.show() # 顯示
你瞧,函數影像就輕鬆地畫出來了,不得不說,Python 真的太好用了。

但是這樣看,這個影像太單調了,我們給它豐富一下細節,對每一條曲線加上一個標籤,將原來的 plt.plot() 方法傳入參數:
plt.plot(x, data1, label="curve1") plt.plot(x, data2, label="curve2")
然後再用方法 plt.legend() 放置標籤的位置:
plt.legend(loc='upper center', bbox_to_anchor=(0.2, 0.95))
其中第一個參數為標籤大概位置,第二個參數是調整標籤的具體位置,然後新的影像為:

但是我對這個影像還不滿意,這個坐標跟我平常見到的坐標不太一樣呀,有什麼辦法可以變成我們常見的坐標嗎?這時候就要發揮出我們的智慧了。
這個影像有四條坐標軸,上下左右各一條,我們只需要把上和右坐標軸隱藏,然後移動剩下兩條坐標軸不就好咯。
ax = plt.gca() # 獲取坐標軸 ax.spines['right'].set_color('none') # 將右坐標軸顏色設置為空白 ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') # 將刻度在 x 軸底部顯示 ax.yaxis.set_ticks_position('left') ax.spines['bottom'].set_position(('data', 0)) # 把影像與坐標軸關聯 ax.spines['left'].set_position(('data', 0))
影像成功的變成了我們想要的樣子:

以下是具體程式碼:
import matplotlib.pyplot as plt x = [-1.0, -0.5, 1.5, 2.5, 4.0, 5.5, 7.0, 9.0, 10.5, 11.5, 13.0, 15.5, 18.0, 20.5, 23.0, 25.5, 28.0, 33.0, 38.0, 43.0] data1 = [0.1, 0.9, 5.6, 7.8, 14.8, 21.2, 26.3, 32.0, 36.6, 39.4, 42.6, 47.9, 52.2, 56.1, 59.8, 63.2, 66.3, 72.2, 77.5, 81.5] data2 = [0.1, 0.2, 2.1, 3.7, 6.8, 9.8, 11.8, 14.9, 16.1, 17.2, 18.6, 20.7, 22.6, 24.4, 26.0, 27.5, 28.9, 31.0, 32.9, 34.3] ax = plt.gca() # 獲取坐標軸 ax.spines['right'].set_color('none') # 將右坐標軸顏色設置為空白 ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') # 將刻度在 x 軸底部顯示 ax.yaxis.set_ticks_position('left') ax.spines['bottom'].set_position(('data', 0)) # 把影像與坐標軸關聯 ax.spines['left'].set_position(('data', 0)) plt.title("curve") # 標題 plt.xlabel("x") # x 軸資訊 plt.ylabel("y") # y 軸資訊 plt.plot(x, data1, label="curve1") plt.plot(x, data2, label="curve2") plt.legend(loc='upper center', bbox_to_anchor=(0.2, 0.95)) plt.show() # 顯示