目錄
目錄
前言
今天我們學習的是條形圖,導入的函數是:
plt.bar() 於 plt.barh
(一)豎值條形圖
(1)說明:
原函數定義:
bar
(x, height, width=0.8, bottom=None, ***, align='center', data=None, **kwargs)
常見的參數屬性
具體參考:官網說明文檔
參數 | 說明 | 類型 |
---|---|---|
x | x坐標 | int,float |
height | 條形的高度 | int,float |
width | 寬度 | 0~1,默認0.8 |
botton | 條形的起始位置 | 也是y軸的起始坐標 |
align | 條形的中心位置 | “center”,"lege"邊緣 |
color | 條形的顏色 | “r","b","g","#123465",默認“b" |
edgecolor | 邊框的顏色 | 同上 |
linewidth | 邊框的寬度 | 像素,默認無,int |
tick_label | 下標的標簽 | 可以是元組類型的字符組合 |
log | y軸使用科學計算法表示 | bool |
orientation | 是豎直條還是水平條 | 豎直:"vertical",水平條:"horizontal" |
(2)源代碼:
"""
默認的是豎值條形圖
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
# 將全局的字體設置為黑體
matplotlib.rcParams['font.family'] = 'SimHei'
# 數據
N = 5
y = [20, 10, 30, 25, 15]
x = np.arange(N)
# 繪圖 x x軸, height 高度, 默認:color="blue", width=0.8
p1 = plt.bar(x, height=y, width=0.5, )
# 展示圖形
plt.show()
(3)輸出效果:
(二)水平條形圖
1.使用bar()繪制:
(1)說明
需要把:orientation="horizontal",然后x,與y的數據交換,再添加bottom=x,即可。
(2)源代碼:
"""
水平條形圖,需要修改以下屬性
orientation="horizontal"
"""
import numpy as np
import matplotlib.pyplot as plt
# 數據
N = 5
x = [20, 10, 30, 25, 15]
y = np.arange(N)
# 繪圖 x= 起始位置, bottom= 水平條的底部(左側), y軸, height 水平條的寬度, width 水平條的長度
p1 = plt.bar(x=0, bottom=y, height=0.5, width=x, orientation="horizontal")
# 展示圖形
plt.show()
(3)輸出效果:
2.使用barh()繪制:
具體可參考:官網說明文檔
(1)說明
使用barh()時,bottom改為left, 然后寬變高,高變寬。
(2)源代碼:
"""
水平條形圖,需要以下屬性
orientation="horizontal"
"""
import numpy as np
import matplotlib.pyplot as plt
# 數據
N = 5
x = [20, 10, 30, 25, 15]
y = np.arange(N)
# 繪圖 y= y軸, left= 水平條的底部, height 水平條的寬度, width 水平條的長度
p1 = plt.barh(y, left=0, height=0.5, width=x)
# 展示圖形
plt.show()
(3)輸出效果:
[圖片上傳失敗...(image-c414f2-1552186154190)]
(三)復雜的條形圖
1.並列條形圖:
(1)說明
我們再同一張畫布,畫兩組條形圖,並且緊挨着就時並列條形圖。
改變x的位置。
(2)源代碼:
import numpy as np
import matplotlib.pyplot as plt
# 數據
x = np.arange(4)
Bj = [52, 55, 63, 53]
Sh = [44, 66, 55, 41]
bar_width = 0.3
# 繪圖 x 表示 從那里開始
plt.bar(x, Bj, bar_width)
plt.bar(x+bar_width, Sh, bar_width, align="center")
# 展示圖片
plt.show()
(3)輸出效果:
2.疊加條形圖:
(1)說明
兩組條形圖是處與同一個x處,並且y是連接起來的。
(2)源代碼:
import numpy as np
import matplotlib.pyplot as plt
# 數據
x = np.arange(4)
Bj = [52, 55, 63, 53]
Sh = [44, 66, 55, 41]
bar_width = 0.3
# 繪圖
plt.bar(x, Bj, bar_width)
plt.bar(x, Sh, bar_width, bottom=Bj)
# 展示圖片
plt.show()
(3)輸出效果:
3.添加圖例於數據標簽的條形圖:
(1)說明
- 對於圖例:
先可選屬性里添加label=“”,標簽
再使用plt.lengd()顯示。
- 對於數據的標簽
使用任意方向的標簽來標注,再由x,y數據確定坐標。
- tick_label=str,用來顯示自定義坐標軸
(2)源代碼:
"""
默認的是豎值條形圖
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
# 將全局的字體設置為黑體
matplotlib.rcParams['font.family'] = 'SimHei'
# 數據
N = 5
y = [20, 10, 30, 25, 15]
x = np.arange(N)
# 添加地名坐標
str1 = ("北京", "上海", "武漢", "深圳", "重慶")
# 繪圖 x x軸, height 高度, 默認:color="blue", width=0.8
p1 = plt.bar(x, height=y, width=0.5, label="城市指標", tick_label=str1)
# 添加數據標簽
for a, b in zip(x, y):
plt.text(a, b + 0.05, '%.0f' % b, ha='center', va='bottom', fontsize=10)
# 添加圖例
plt.legend()
# 展示圖形
plt.show()