解決中文問題 | Python 資料可視化庫 Matplotlib 快速入門之九
其他輔助顯示層完善折線圖
添加網格顯示
為了更加清楚的觀察圖形對應的值
添加代碼:
plt.grid(True, linestyle = "--", alpha = 0.5)
執行結果:

添加描述資訊
添加x軸,y軸描述資訊及标題
plt.xlable("時間變化")
plt.ylable("溫度變化")
plt.title("某城市11點到12點每分鐘的溫度變化狀況")
此時想要再添加一個城市的資訊,該如何操作呢?
要想給原始的折線圖再添加一個資訊,需要在圖像層做出修改。
完善原始折線圖(圖像層)
需求:再添加一個城市的溫度變化
收集到北京當天溫度變化情況,溫度在1度到3度。
多次plot
怎麼去添加另一個在同一坐标系當中的不同圖形, 其實很簡單隻需要再次plot即可, 但是需要區分線條, 如下:
準備資料,添加代碼:
y_beijing = [random.uniform(1, 3) for i in x]
plt.plot(x, y_beijing)
plt.title("上海、北京11點到12點每分鐘的溫度變化狀況")
如果此時不想是預設的顔色,我們也可以進行改變。
plt.plot(x, y_shanghai, color = "r")
plt.plot(x, y_beijing, color = "b")
此時改變線條風格:
plt.plot(x, y_shanghai, color = "r", linestyle = "--")
還有一些其它的風格,我們可以來看一下。
設定圖形風格
顔色字元 | 風格字元 |
---|---|
r 紅色 | - 實線 |
g 綠色 | -- 虛線 |
b 藍色 | -. 點劃線 |
w 白色 | : 點虛線 |
c 青色 | ' ' 留白、空格 |
m 洋紅 | |
y 黃色 | |
k 黑色 |
我們還需要給圖加上圖例來完善。
顯示圖例
修改代碼:
plt.plot(x, y_shanghai, color = "r", linestyle = "-.", label = "上海")
plt.plot(x, y_beijing, color = "b", label = "北京")
plt.legend()
此時我們用的是預設的方式。
- 注意:如果隻在plt.plot()中設定label還不能最終顯示出圖例, 還需要通過plt.legend()将圖例顯示出來。
我們也可以調整圖例的位置。
plt.legend(loc = "lower left")
或者
plt.legend(loc = 4)
圖例位置代碼:
Location String | Location Code |
---|---|
'best' | |
'upper right' | 1 |
'upper left' | 2 |
'lower left' | 3 |
'lower right' | 4 |
'right' | 5 |
'center left' | 6 |
'center right' | 7 |
'lower center' | 8 |
'upper center' | 9 |
'center' | 10 |
完整代碼:
import random
# 1、準備資料 x,y
x = range(60)
y_shanghai = [random.uniform(15, 18) for i in x]
y_beijing = [random.uniform(1, 3) for i in x]
# 2、建立畫布
plt.figure(figsize=(20, 8), dpi=80)
# 3、繪制圖像
plt.plot(x, y_shanghai, color = "r", linestyle = "-.", label = "上海")
plt.plot(x, y_beijing, color = "b", label = "北京")
# 顯示圖例
plt.legend()
# 修改x,y刻度
# 準備x的刻度說明
x_lable = ["11點{}分".format(i) for i in x]
plt.xticks(x[::5], x_lable[::5])
plt.yticks(range(0, 40, 5))
# 添加網格顯示
plt.grid(True, linestyle = "--", alpha = 0.5)
# 添加描述資訊
plt.xlable("時間變化")
plt.ylable("溫度變化")
plt.title("上海、北京11點到12點每分鐘的溫度變化狀況")
# 4、顯示圖
plt.show()
配套視訊課程,點選這裡檢視
擷取更多資源請訂閱
Python學習站