随笔 - 384  文章 - 0  评论 - 35  阅读 - 142万

画堆积柱形图

一、plt画堆积柱形图

只需要这个一个参数(bottom=y)就OK了

复制代码
import matplotlib.pyplot as plt
import matplotlib as mpl

mpl.rcParams["font.sans-serif"] = ["SimHei"]
mpl.rcParams["axes.unicode_minus"] = False

x = [1, 2, 3, 4, 5]
y = [6, 10, 4, 5, 1]
y1 = [2, 6, 3, 8, 5]

plt.figure(figsize=(16,12))
plt.bar(x, y, align="center", color="#66c2a5", tick_label=["A", "B", "C", "D", "E"], label="班级A")
plt.bar(x, y1, align="center", bottom=y, color="#8da0cb", label="班级B")

plt.xlabel("测试难度")
plt.ylabel("试卷份数")

plt.legend()

plt.show()
复制代码

 

二、pandas中df.plot()画图

首先创造数据

复制代码
#模拟生成数据集的方法

import pandas as pd
import numpy as np 

boolean=[True,False]
gender=['','']
color=['green','blue','yellow']
tmp_1203=pd.DataFrame({'height':np.random.randint(150,190,100),
                   'weight':np.random.randint(40,90,100),
                   'smoker':[boolean[x] for x in np.random.randint(0,2,100)],
                   'gender':[gender[x] for x in np.random.randint(0,2,100)],
                   'age':np.random.randint(15,90,100),
                   'color':[color[x] for x in np.random.randint(0,len(color),100)]})
复制代码

首先这样子尝试

tmp_1203.iloc[0:5,:][['gender','age']].plot(kind='bar', stacked=True)

 

 

 看着样子不行,再次尝试

tmp_1203.iloc[0:5,:][['gender','age','weight']].set_index('gender').T.plot(kind='bar', stacked=True)

 

 看着还行,但是感觉不是很对,或许我们可以首先聚合,然后在尝试

tmp_1203.groupby('gender').sum().T.plot(kind='bar', stacked=True)

 样子看着是对上了,可是还差点感觉

使用新的数据

import pandas as pd 
dates=pd.date_range('20130101',periods=6)
df=pd.DataFrame(np.random.randint(0,20,(6,4)),index=dates,columns=list('ABCD'))
df.index=pd.date_range('20130101',periods=df.shape[0])
df.index=pd.date_range('20130101',periods=len(df))

df.plot(kind='bar', stacked=True)

 感觉对上了,装置再试一下

df.T.plot(kind='bar', stacked=True)

 总结来了:反正就是索引index作为行x轴(所以想办法将你所需的转为索引,groupby,或者直接set_index('xx')),column作为堆叠类,切要主要参数stacked=True然后就可以画出想要的结果

三、seaborn

找了好多资料,还是没有方法

import seaborn as sns
sns.barplot(x=df.index,y='A',color = "red",data=df)
sns.barplot(x=df.index,y='C',color = "green",data=df)

 

 

 可以看出,其实第二个图的值如果比第一个图的值大,那么第一个图会被覆盖住,如果小,就会显示第一个图,正由于这种特性,我们可以将第一个图设置为总和,然后第二张图再设定为原来的第一张图,看代码

sns.set_style("white")
sns.set_context({"figure.figsize": (12, 8)})
#Plot 2 - overlay - "bottom" series
c = sns.barplot(x=df.index,y=df['C']+df['A'],color = "green")
sns.barplot(x=df.index,y='A',color = "red",data=df)

 看着效果还可以,就是逗了个圈

 

posted on   小小喽啰  阅读(1864)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示