'''
柱狀圖、堆疊圖
plt.plot(kind='bar/barh') , plt.bar()
'''
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 柱狀圖與堆疊圖
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',ax = axes[0],color = 'k',grid = True,alpha = 0.5) # ax參數 → 選擇第幾個子圖
# 單系列柱狀圖方法一:plt.plot(kind='bar/barh')
df.plot(kind='bar',ax = axes[1],grid = True )
# 多系列柱狀圖
df.plot.bar(ax = axes[2],grid = True ,stacked=True)
# df.plot(kind='bar',ax = axes[2],grid = True ,stacked=True)
# 多系列堆疊圖
# stacked → 堆疊
df.plot.barh(ax = axes[3],grid = True,stacked=True,colormap = 'BuGn_r')
# 新版本plt.plot.<kind>
# 柱狀圖 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 :wx/y方向error bar
for i,j in zip(x,y1):
plt.text(i-0.2,j-0.15,'%.2f' % j, color = 'white')
for i,j in zip(x,y2):
plt.text(i-0.2,j-0.15,'%.2f' % -j, color = 'black')
# 給圖添加text
# zip() 函數用於將可迭代的對象做爲參數,將對象中對應的元素打包成一個個元組,而後返回由這些元組組成的列表。
# 外嵌圖表plt.table()
# table(cellText=None, cellColours=None,cellLoc='right', colWidths=None,rowLabels=None, rowColours=None, rowLoc='left',
# colLabels=None, colColours=None, colLoc='center',loc='bottom', bbox=None)
data = [[ 66386, 174296, 75131, 577908, 32015],
[ 58230, 381139, 78045, 99308, 160454],
[ 89135, 80552, 152558, 497981, 603535],
[ 78415, 81858, 150656, 193263, 69638],
[139361, 331509, 343164, 781380, 52269]]
columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')
rows = ['%d year' % x for x in (100, 50, 20, 10, 5)]
df = pd.DataFrame(data,
columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail'),
index = ['%d year' % x for x in (100, 50, 20, 10, 5)]
)
print(df)
df.plot(kind='bar',grid = True,colormap='Blues_r',stacked=True,figsize=(8,3))
# 建立堆疊圖
plt.table(cellText = data,
cellLoc='center',
cellColours = None,
rowLabels = rows,
rowColours = plt.cm.BuPu(np.linspace(0, 0.5,5))[::-1], # BuPu可替換成其餘colormap
colLabels = columns,
colColours = plt.cm.Reds(np.linspace(0, 0.5,5))[::-1],
rowLoc='right',
loc='bottom')
# cellText:表格文本
# cellLoc:cell內文本對齊位置
# rowLabels:行標籤
# colLabels:列標籤
# rowLoc:行標籤對齊位置
# loc:表格位置 → left,right,top,bottom
plt.xticks([])
# 不顯示x軸標註