Python matplotlib 畫圖入門 08 柱形圖(直方圖,柱狀圖,條狀圖,條形圖)


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM