【matplotlib】2.條形圖

條形圖

  • plt.bar()
matplotlib.pyplot.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)[source]

1.參數

參數 含義 類型
x x軸含義 sequence of scalars
height 對應的條形的高度 scalar or sequence of scalars
width 條形的寬 scalar or array-like, optional,默認0.8

2.例子

2.1 例1 普通條形圖

import matplotlib.pyplot as plt
import numpy as np

x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]

plt.bar(x, height=y)
plt.show()

在這裏插入圖片描述

2.2 例2 x軸爲字符串

import matplotlib.pyplot as plt
import numpy as np

x = ['a', 'b', 'c', 'd', 'e']
y = [10, 20, 30, 40, 50]

plt.bar(x, height=y)
plt.show()

在這裏插入圖片描述

2.3 並列條形圖

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5])   # 轉換成array之後便於加width
y1 = [10, 20, 30, 40, 50]
y2 = [20, 40, 60, 80, 100]

plt.bar(x, height=y1, width=0.3)
plt.bar(x+0.3, height=y2, width=0.3)
plt.show()

在這裏插入圖片描述

2.4 水平條形圖

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5])  
y1 = [10, 20, 30, 40, 50]


# 其中添加最後一個orientation之後,水平方向的參數和豎直方向的參數就反過來了
# 繪圖 x= 起始位置, bottom= 水平條的底部(左側), y軸, height 水平條的寬度, width 水平條的長度
plt.bar(x=0, bottom=x, height=0.5, width=y1, orientation="horizontal")
plt.show()

在這裏插入圖片描述

2.5 疊加條形圖

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5])   # 轉換成array之後便於加width
y1 = [10, 20, 30, 40, 50]
y2 = [20, 40, 60, 80, 100]

lt.bar(x, height=y1, width=0.3)
plt.bar(x, height=y2, width=0.3, bottom=y1)  # y1開始就行了
plt.show()

在這裏插入圖片描述

3.更高階的條形圖

除了上面那些之外,還有更多高級的條形圖,不過有些可能不會經常用到。這些在官網上也都有例子。

比如:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章