Python+matplotlib實現堆疊圖的繪制
更新時間:2022年03月08日 14:09:43 作者:渴望成為寂寞勝者
Matplotlib作為Python的2D繪圖庫,它以各種硬拷貝格式和跨平臺的交互式環(huán)境生成出版質量級別的圖形。本文將利用Matplotlib庫繪制堆疊圖,感興趣的可以了解一下
注:本文的所有數據請移步—— 參考數據
一、水平堆疊圖
堆疊圖其實就是柱狀圖的一種特殊形式
from matplotlib import pyplot as plt plt.style.use('seaborn') plt.figure(figsize=(15,9)) plt.rcParams.update({'font.family': "Microsoft YaHei"}) plt.title("中國票房2021TOP9") plt.bar(cnbodfgbsort.index,cnbodfgbsort.PERSONS) plt.bar(cnbodfgbsort.index,cnbodfgbsort.PRICE) plt.bar(cnbodfgbsort.index,cnbodfgbsort.points) plt.show()
堆疊圖效果
可以看到有部分藍色的數據被遮擋了,如果我們想全部展現,可以:
index_x=np.arange(len(cnbodfgbsort.index)) index_x w=0.15
from matplotlib import pyplot as plt plt.style.use('classic') plt.figure(figsize=(15,9)) plt.rcParams.update({'font.family': "Microsoft YaHei"}) plt.title("中國票房2021TOP9") plt.bar(index_x,cnbodfgbsort.PERSONS,width=w) plt.bar(index_x+w,cnbodfgbsort.PRICE,width=w) plt.bar(index_x+2*w,cnbodfgbsort.points,width=w) plt.show()
可以看到Excel的數據源當中BO與PRICE和PERSONS的數字相差過大,如果做堆疊圖的話,BO會將其他的都進行覆蓋,無法顯示好的效果:
因為數據相差實在太大,我們可以直接讓BO除以1000:
from matplotlib import pyplot as plt plt.style.use('classic') plt.figure(figsize=(15,9)) plt.rcParams.update({'font.family': "Microsoft YaHei"}) plt.title("中國票房2021TOP9") plt.bar(cnbodfgbsort.index,cnbodfgbsort.PERSONS) plt.bar(cnbodfgbsort.index,cnbodfgbsort.PRICE) plt.bar(cnbodfgbsort.index,cnbodfgbsort.BO/1000) plt.bar(cnbodfgbsort.index,cnbodfgbsort.points) plt.show()
from matplotlib import pyplot as plt plt.style.use('classic') plt.figure(figsize=(15,9)) plt.rcParams.update({'font.family': "Microsoft YaHei"}) plt.title("中國票房2021TOP9") plt.bar(index_x-w,cnbodfgbsort.BO/1000,width=w) # 直接讓BO除以1000 plt.bar(index_x,cnbodfgbsort.PERSONS,width=w) plt.bar(index_x+w,cnbodfgbsort.PRICE,width=w) plt.bar(index_x+2*w,cnbodfgbsort.points,width=w) plt.show()
二、波浪形堆疊圖
labels=['戰(zhàn)爭','愛情','動畫','動作','驚悚','劇情'] colors=['tan','violet','turquoise','tomato','teal','steelblue'] plt.stackplot(cnbodfgbsort.index,cnbodfgbsort.PRICE,cnbodfgbsort.PERSONS,cnbodfgbsort.points,labels=labels,colors=colors)
labels=['戰(zhàn)爭','愛情','動畫','動作','驚悚','劇情'] colors=['tan','violet','turquoise','tomato','teal','steelblue'] plt.stackplot(cnbodfgbsort.index,cnbodfgbsort.PRICE,cnbodfgbsort.BO/900,cnbodfgbsort.PERSONS,cnbodfgbsort.points,labels=labels,colors=colors)
三、加上數據標簽
plt.legend()
labels=['票房','票價','人次','評分'] colors=['tan','violet','turquoise','tomato','teal','steelblue'] plt.stackplot(cnbodfgbsort.index,cnbodfgbsort.PRICE,cnbodfgbsort.BO/900,cnbodfgbsort.PERSONS,cnbodfgbsort.points,labels=labels,colors=colors) plt.legend()
到此這篇關于Python+matplotlib實現堆疊圖的繪制的文章就介紹到這了,更多相關Python matplotlib堆疊圖內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章: