画堆积柱形图
一、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)
看着效果还可以,就是逗了个圈
分类:
画图(sns,plt,plot)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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训练数据并当服务器共享给他人