1. 程式人生 > 其它 >Python matplotlib 畫圖入門 08 柱形圖

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(["Run-1", "Run-2", "Run-3", "C-Run"])
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