如何按色调/图例组用百分比注释分组条形图

2024-01-24

我想根据色调在条形顶部添加百分比。这意味着所有红色和蓝色条分别等于 100%。

我可以使蓝色条等于 100%,但红色条不能。哪些部分需要修改?

导入和样本数据

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# sample data
np.random.seed(365)
rows = 100000
data = {'Call_ID': np.random.normal(10000, 8000, size=rows).astype(int),
        'with_client_nmbr': np.random.choice([False, True], size=rows, p=[.17, .83]),
        'Type_of_Caller': np.random.choice(['Agency', 'EE', 'ER'], size=rows, p=[.06, .77, .17])}
all_call = pd.DataFrame(data)

   Call_ID  with_client_nmbr Type_of_Caller
0    11343              True             EE
1    14188              True         Agency
2    16539             False             EE
3    23630              True             ER
4    -7175              True             EE

汇总和绘图

df_agg= all_call.groupby(['Type_of_Caller','with_client_nmbr'])['Call_ID'].nunique().reset_index()

ax = sns.barplot(x='Type_of_Caller', y='Call_ID', hue='with_client_nmbr',
                 data=df_agg,palette=['orangered', 'skyblue'])

hue_order = all_call['with_client_nmbr'].unique()
df_f = sum(all_call.query("with_client_nmbr==False").groupby('Type_of_Caller')['Call_ID'].nunique())
df_t = sum(all_call.query("with_client_nmbr==True").groupby('Type_of_Caller')['Call_ID'].nunique())

for bars in ax.containers:
    if bars.get_label() == hue_order[0]:
        group_total = df_f
    else:
        group_total = df_t
    for p in ax.patches:
        width = p.get_width()
        height = p.get_height()
        x, y = p.get_xy()
        ax.annotate(f'{(height/group_total):.1%}', (x + width/2, y + height*1.02), ha='center')
plt.show()
  • print(hue_order) is ['False', 'True']

  • It's typically not required to use seaborn to plot grouped bars, it's just a matter of shaping the dataframe, usually with .pivot https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html or .pivot_table https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot_table.html. See How to create a grouped bar plot https://stackoverflow.com/q/47796264/7758804 for more examples.
    • Using pandas.DataFrame.plot https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html在这种情况下,使用宽数据框比使用长数据框更容易seaborn.barplot https://seaborn.pydata.org/generated/seaborn.barplot.html,因为柱/条顺序和totals重合。
    • 这将代码从 16 行减少到 8 行。
  • 看到这个answer https://stackoverflow.com/a/68851142/7758804用于将注释添加为总体的百分比。
  • 测试于python 3.8.11, pandas 1.3.1, and matplotlib 3.4.2

导入和数据帧转换

import pandas as pd
import matplotlib.pyplot as plt

# transform the sample data from the OP with pivot_table
dfp = all_call.pivot_table(index='Type_of_Caller', columns='with_client_nmbr', values='Call_ID', aggfunc='nunique')

# display(dfp)
with_client_nmbr  False   True
Type_of_Caller                
Agency              994   4593
EE                10554  27455
ER                 2748  11296

Use matplotlib.pyplot.bar_label https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar_label.html

  • 需要matplotlib >= 3.4.2
  • 每列按顺序绘制,并且pandas.Series由...制作df.sum()与数据框列的顺序相同。所以,zip totals到绘图容器并使用该值,tot, in labels按色相组计算百分比。
  • Add custom annotations based on percent by hue group, by using the labels parameter.
    • (v.get_height()/tot)*100在列表理解中,计算百分比。
  • 看到这个answer https://stackoverflow.com/a/67561982/7758804对于其他选项使用.bar_label
# get the total value for the column
totals = dfp.sum()

# plot
p1 = dfp.plot(kind='bar', figsize=(8, 4), rot=0, color=['orangered', 'skyblue'], ylabel='Value of Bar', title="The value and percentage (by hue group)")

# add annotations
for tot, p in zip(totals, p1.containers):
    
    labels = [f'{(v.get_height()/tot)*100:0.2f}%' for v in p]
    
    p1.bar_label(p, labels=labels, label_type='edge', fontsize=8, rotation=0, padding=2)

p1.margins(y=0.2)
plt.show()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何按色调/图例组用百分比注释分组条形图 的相关文章

随机推荐

  • 使用 xlrd 在 Python 3 中将 xls 转换为 csv

    我使用带有 xlrd 和 csv 模块的 Python 3 3 将 xls 文件转换为 csv 这是我的代码 import xlrd import csv def csv from excel wb xlrd open workbook M
  • 如何以树(多维数组)的形式存储和检索 Apache Solr 字段?

    我需要将结果存储和检索为多维树 而不是平面 键 gt 值 对 让我用一个例子来解释 我有很多类别的产品 每个类别都有一个优先级值 样本结构 name Sample Product categories category Category 1
  • NOT IN 查询不起作用,SQL Server 2008

    之前查询的第一部分not in运行并给我一个包含 100 条记录的列表 第二个查询运行并给出 75 条记录的列表 我正在尝试编写的查询not in是获取一个结果集中的记录 而不是另一个结果集中的记录 我得到的错误是incorrect syn
  • 如何查找我的系统中安装了哪个版本的 TensorFlow?

    我需要找到我安装的 TensorFlow 版本 我正在使用 Ubuntu 16 04 长期支持 这取决于您安装 TensorFlow 的方式 我将使用与TensorFlow的安装说明 https www tensorflow org ver
  • SharePoint Designer 工作流程 - 提示和资源?

    我正在努力修改一些现有的 SPD WF 并努力解决一些概念 包括为什么 2 个看起来相似的 WF 不会产生相同的输出 你们中是否有人使用过 SharePoint Designer 工作流并知道任何好的资源 比 MSDN 介绍更详细 或有关此
  • 如何隐藏 UIImagepickercontroller 中的状态栏?

    我是 iOS 开发新手 我试图隐藏状态栏UIImagePickerController 每当我单击 拍照 时 就会出现状态栏 它并不隐藏 我希望状态栏仅隐藏在UIImagePickerController 这是我的代码 IBAction t
  • 在机器对机器场景中使用 MSAL 作为 CSP

    我正在尝试使用官方 nuget 库来使用 GraphAPI https github com microsoftgraph msgraph sdk dotnet https github com microsoftgraph msgraph
  • 播放框架WS url空间

    我在 play 框架 2 3 3 中调用 WS url 时遇到问题 其中 url 包含空格 所有其他字符均自动进行 url 编码 但空格除外 当我尝试将所有空格更改为 20 时 WS 由于 字符而将其转换为 2520 对于空格 我得到了 j
  • 为什么锁定 std::mutex 两次“未定义行为”?

    按照这个article http www devx com SpecialReports Article 38883 1954 如果您尝试从同一线程两次锁定非递归互斥锁 而中间没有解锁 则会出现未定义的行为 我非常天真的想法告诉我为什么他们
  • Neo4j 2.0 双类型转储

    在 Neo4j 2 0 社区 上 当我转储包含一些具有 Double 类型属性的节点的数据库时 我获得一个具有科学记数法值的文件 ex 1 43524185E8 导入此文件时 neo4j shell 失败并出现以下错误 Invalid in
  • 在 Eclipse (App Engine) 项目中包含 JAR 文件

    我今天和昨天几个小时都在寻找这个问题的解决方案 所以我决定在这里解决它 尽管这似乎是一个愚蠢的问题 情况 我在 Eclipse Java EE 中设置了一个 Google AppEngine 项目 它已经存在了好几个星期 一切都运行良好 我
  • Linux 上的共享库有哪些好的做法?

    我最近阅读了很多有关 Linux 上共享库的内容 以下是我学到的内容 共享库应该嵌入一个soname包括其主要版本号 就像是 libfoo so 1 其真实文件名还应包含次要版本号 就像是 libfoo so 1 0 当库文件被复制到时 比
  • 如何动态重新加载 Oracle APEX 5.0 树

    当触发事件 例如单击按钮 时 我需要使用新参数重新加载完整树 设置项目值并且需要在 Tree SQL 中使用新项目值 当我尝试使用 刷新 操作刷新树区域时 树节点不刷新 树小部件支持一整套高级操作 问题是 apex 团队从未向开发人员公开过
  • 时间轴值在某些 ggplot 图中不正确,但在其他图中则不然

    Forum 这是我的数据的样子 gt data cvg Source local data frame 938 x 5 Date Day Time Parameter Value time fctr time chr dbl 1 2016
  • 什么 Java 方法接受 int 并返回 +1 或 -1?

    什么 Java 方法需要一个int并返回 1或 1 其判断标准是是否int是正的还是负的 我浏览了文档 但我不擅长阅读它 所以找不到它 我知道我在某处见过它 Integer signum int i http java sun com ja
  • 将参数传递给BAT文件并双击运行

    我想将两个文件路径 对于 Windows 作为命令行参数传递给脚本 在 Windows 中 如果我们右键单击一个文件 我们可以看到 属性 选项 并且在 常规 选项卡下显示像 test bat 这样的文件名 我们可以从那里传递参数吗 实际上我
  • 了解Elasticsearch的write_consistency和quorum规则

    根据elasticsearch文档 write consistency级别仲裁的规则是 法定人数 gt 副本 2 1 使用 ES 0 19 10 在具有 16 个分片 3 个副本的设置中 我们将得到 16 个主分片 48 个复制品 运行 2
  • 带队列的长时间运行的 REST API

    我们正在实现一个 REST API 它将启动多个长时间运行的后端任务 我一直在阅读 RESTful Web Services Cookbook 建议返回 HTTP 202 Accepted 并带有指向正在处理的任务的 Content Loc
  • 使用 RxSwift、驱动程序并绑定到 [关闭]

    Closed 这个问题需要细节或清晰度 help closed questions 目前不接受答案 我第一次问问题 我正在学习RxSwift 如何使用bind to和driver driver和bind to有什么区别 现在还有谁在学习Rx
  • 如何按色调/图例组用百分比注释分组条形图

    我想根据色调在条形顶部添加百分比 这意味着所有红色和蓝色条分别等于 100 我可以使蓝色条等于 100 但红色条不能 哪些部分需要修改 导入和样本数据 import pandas as pd import numpy as np impor