Matplotlib 柱形圖(直方圖,柱狀圖)
我們可以使用 pyplot 中的 bar() 方法來繪制柱形圖。
bar() 方法語法格式如下:
matplotlib.pyplot.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)
參數說明:
x:浮點型數組,柱形圖的 x 軸數據。
height:浮點型數組,柱形圖的高度。
width:浮點型數組,柱形圖的寬度。
bottom:浮點型數組,底座的 y 坐標,默認 0。
align:柱形圖與 x 坐標的對齊方式,'center' 以 x 位置為中心,這是默認值。 'edge':將柱形圖的左邊緣與 x 位置對齊。要對齊右邊緣的條形,可以傳遞負數的寬度值及 align='edge'。
**kwargs::其他參數。
以下實例我們簡單實用 bar() 來創建一個柱形圖:
實例
import matplotlib.pyplot as plt import numpy as np x = np.array(["Run-1", "Run-2", "Run-3", "C-Run"]) y = np.array([12, 22, 6, 18]) plt.bar(x,y) plt.show()
顯示結果如下:
垂直方向的柱形圖可以使用 barh() 方法來設置:
實例
import matplotlib.pyplot as plt import numpy as np x = np.array(["Run-1", "Run-2", "Run-3", "C-Run"]) y = np.array([12, 22, 6, 18]) plt.barh(x,y) plt.show()
顯示結果如下:
設置柱形圖顏色:
實例
import matplotlib.pyplot as plt import numpy as np x = np.array(["Run-1", "Run-2", "Run-3", "C-Run"]) y = np.array([12, 22, 6, 18]) plt.bar(x, y, color = "#4CAF50") plt.show()
顯示結果如下:
自定義各個柱形的顏色:
實例
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["Cat1", "Cat2", "Cat3", "Cat4"])
y = np.array([12, 22, 6, 18])
plt.bar(x, y, color = ["#4CAF50","red","hotpink","#556B2F"])
plt.show()
顯示結果如下:
設置柱形圖寬度,bar() 方法使用 width 設置,barh() 方法使用 height 設置 height
實例
import matplotlib.pyplot as plt import numpy as np x = np.array(["Run-1", "Run-2", "Run-3", "C-Run"]) y = np.array([12, 22, 6, 18]) plt.bar(x, y, width = 0.1) plt.show()
顯示結果如下:
實例
import matplotlib.pyplot as plt import numpy as np x = np.array(["Run-1", "Run-2", "Run-3", "C-Run"]) y = np.array([12, 22, 6, 18]) plt.barh(x, y, height = 0.1) plt.show()
顯示結果如下:
REF
https://www.runoob.com/matplotlib/matplotlib-bar.html