目錄html
今天咱們學習的是條形圖,導入的函數是:python
plt.bar() 於 plt.barh算法
原函數定義:api
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" |
""" 默認的是豎值條形圖 """ 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()
須要把:orientation="horizontal",而後x,與y的數據交換,再添加bottom=x,便可。字體
""" 水平條形圖,須要修改如下屬性 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()
具體可參考:官網說明文檔code
使用barh()時,bottom改成left, 而後寬變高,高變寬。htm
""" 水平條形圖,須要如下屬性 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()
[圖片上傳失敗...(image-c414f2-1552186154190)]blog
咱們再同一張畫布,畫兩組條形圖,而且緊挨着就時並列條形圖。
改變x的位置。
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()
兩組條形圖是處與同一個x處,而且y是鏈接起來的。
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()
- 對於圖例:
先可選屬性裏添加label=「」,標籤
再使用plt.lengd()顯示。
- 對於數據的標籤
使用任意方向的標籤來標註,再由x,y數據肯定座標。
- tick_label=str,用來顯示自定義座標軸
""" 默認的是豎值條形圖 """ 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()