我正在try 以数据透视表的方式对图表进行分组. 我想用[‘Post_Datetime’,‘Claimed’]以百分比的方式使用Pandas /matplotlib来绘制我的数据图表,其中图表条将导致我的True/False‘Claimed’数据之间的100%分割.

这是我的数据库中的摘录:

post_datetime,claimed,percent,claimed_pct,unclaimed_pct
2016,True,1.0,1.0,
2017,True,1.0,1.0,
2018,False,0.25342,,0.25342
2018,True,0.74658,0.74658,
2019,False,0.3971,,0.3971
2019,True,0.6029,0.6029,
2020,False,0.44128,,0.44128
2020,True,0.55872,0.55872,
2021,False,0.5594,,0.5594
2021,True,0.4406,0.4406,
2022,False,0.5316,,0.5316
2022,True,0.4684,0.4684,

到目前为止,我使用下面的代码得到的最好的结果是一个紧随其后的条形图(我想要100%的条形图,分为比例或True和False‘claiemd’,它在我的数据库中由‘Percent’定义.


    ax = year_claim_df.plot(x='post_datetime',
                       y='claimed_pct',
                       kind='bar',
                       color='red'

                       )
    year_claim_df.plot(x='post_datetime',
                       y='unclaimed_pct',
                       kind='bar',
                       color='blue',
                       ax=ax

                       )
    plt.show()

这是我得到的图表:

enter image description here But I would lile all bars to 1 or 100%, being split colored using my true/false 'claimed' column and by the proportion of my 'percent' column

I would like the chart to be in that fashion (not my data): enter image description here

感谢您的帮助.最好的

推荐答案

pivotrename相加,然后使用DataFrame.plot.bar:

(df.pivot('post_datetime','claimed','percent')
   .rename(columns={True:'claimed_pct',False:'unclaimed_pct'})
   .plot.bar(stacked=True, color=['red','blue']))

pic

Python-3.x相关问答推荐

为什么我必须在绘制椭圆时代码等于两次?''

我有个问题继承遗产合伙人

如何将CSV或FDF数据解析到Python词典并注入到模板PDF表单中?

网站抓取:当我使用Chrome DevTools中的网络选项卡时,找不到正确的URL来提供我想要的数据

将字符串转换为python日期时间时出错

Django 3.2/Django-cms 3.11:查找错误:型号帐户.客户用户未注册

使用递归将int转换为字符串

不同的焦点顺序和堆叠顺序 tkinter

Python (pandas) - 判断一个 df 中的值是否在另一个(不相等)df 中的任何对之间

以编程方式映射 uniprot ID 时如何解决 400 客户端错误?

找到操作系统的图片文件夹的 CLI

使用正则表达式捕获组解析地址

从 h264 帧解析数据包时 PyAV 不一致

在初始化之前禁用`__setattr__`的干净方法

使用 pytest.fixture 返回模拟对象的正确方法

AttributeError:LinearRegression 对象没有属性coef_

Python在OrderedDict中 Select 第i个元素

SQLAlchemy:如果不存在则创建模式

为什么异步库比这个 I/O 绑定操作的线程慢?

如何更改 tkinter 文本小部件中某些单词的 colored颜色 ?