Python數據分析實戰【第三章】3.7-Matplotlib柱狀圖、堆疊圖【python】

1.柱狀圖與堆疊圖

fig,axes = plt.subplots(4,1,figsize = (10,10))
s = pd.Series(np.random.randint(0,10,16),index = list('abcdefghijklmnop'))  
df = pd.DataFrame(np.random.rand(10,3), columns=['a','b','c'])

s.plot(kind='bar',color = 'k',grid = True,alpha = 0.5,ax = axes[0])  # ax參數 → 選擇第幾個子圖
# 單系列柱狀圖方法一:plt.plot(kind='bar/barh')

df.plot(kind='bar',ax = axes[1],grid = True,colormap='Reds_r')
# 多系列柱狀圖

df.plot(kind='bar',ax = axes[2],grid = True,colormap='Blues_r',stacked=True) 
# 多系列堆疊圖
# stacked → 堆疊

df.plot.barh(ax = axes[3],grid = True,stacked=True,colormap = 'BuGn_r')
# 新版本plt.plot.<kind>

在這裏插入圖片描述
在這裏插入圖片描述

2.柱狀圖 plt.bar()


plt.figure(figsize=(10,4))
x = np.arange(10)
y1 = np.random.rand(10)
y2 = -np.random.rand(10)

plt.bar(x,y1,width = 1,facecolor = 'yellowgreen',edgecolor = 'white',yerr = y1*0.1)
plt.bar(x,y2,width = 1,facecolor = 'lightskyblue',edgecolor = 'white',yerr = y2*0.1)
# x,y參數:x,y值
# width:寬度比例
# facecolor柱狀圖裏填充的顏色、edgecolor是邊框的顏色
# left-每個柱x軸左邊界,bottom-每個柱y軸下邊界 → bottom擴展即可化爲甘特圖 Gantt Chart
# align:決定整個bar圖分佈,默認left表示默認從左邊界開始繪製,center會將圖繪製在中間位置
# xerr/yerr :x/y方向error bar

for i,j in zip(x,y1):
    plt.text(i+0.3,j-0.15,'%.2f' % j, color = 'white')
for i,j in zip(x,y2):
    plt.text(i+0.3,j+0.05,'%.2f' % -j, color = 'white')
# 給圖添加text
# zip() 函數用於將可迭代的對象作爲參數,將對象中對應的元素打包成一個個元組,然後返回由這些元組組成的列表。

在這裏插入圖片描述

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