欢迎光临
我们一直在努力

Python+matplotlib如何绘制堆叠图

这篇文章主要介绍Python+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=['战争','爱情','动画','动作','惊悚','剧情'] 
colors=['tan','violet','turquoise','tomato','teal','steelblue'] 
plt.stackplot(cnbodfgbsort.index,cnbodfgbsort.PRICE,cnbodfgbsort.PERSONS,cnbodfgbsort.points,labels=labels,colors=colors)

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()
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如何绘制堆叠图”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注云搜网行业资讯频道!

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。