如何在Python中从数据帧绘制简单绘图?

2024-09-28 18:52:05 发布

您现在位置:Python中文网/ 问答频道 /正文

Hellow我有如下数据帧:

df= pd.DataFrame({"target1" : [10, 0, 15, 10], "target2" : [50, 0, 20, 0], "ID" : ["1", "2", "3", "4"]})

我需要创建一个绘图(条形图或饼图),它将显示ID中有多少%有target1,有多少target2,还有多少其他的(既不是target1也不是target2)

我需要的结果如下:
T1 75%,因为4个ID中有3个具有target1
T2 50%,因为4个ID中的2个具有target2
其他25%,因为4中的1既没有target1也没有target2

如果可能的话,我需要列和图例的百分比说明

enter image description here


Tags: 数据id绘图dataframedfpd百分比条形图
2条回答

我的解决方案

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({"target1": [10, 0, 15, 10], "target2": [50, 0, 20, 0], "ID": ["1", "2", "3", "4"]})
all = len(df["ID"])
value = [0, 0, 0]
for i in range(0, all):
    b = False
    if df["target1"][i] != 0:
        value[0] += 1
        b = True
    if df["target2"][i] != 0:
        value[1] += 1
        b = True
    if not b:
        value[2] += 1

# or you can use this
# value = [float(len([col for col in df["target1"] if col > 0])) / all * 100,
#            float(len([col for col in df["target2"] if col > 0])) / all * 100]
value = [(float(col) / all * 100) for col in value]
num_list = value
plt.bar(range(len(num_list)), num_list,
        tick_label=["target1 " + str(value[0]) + "%",
                    "target2 " + str(value[1]) + "%",
                    "default " + str(value[2]) + "%"])
plt.show()

effect

  • ^{}作为'ID',因为我们不想对该列进行计算
  • 检查不等于0^{})的项目数
  • 通过100获取^{}^{}tiply以转换为百分比
  • 创建条^{},使用rot=1,否则xticks将是垂直的

要对条形图进行注释,请执行以下操作:

  • 保存plot对象,循环通过patches
  • get_height(百分比值),并通过添加'%'符号将其格式化为适当的标签
  • get_x位置和{}按略大于1的因子对其进行缩放,以便标签不会与条相交
>>> ax = df.set_index('ID').ne(0).mean().mul(100).plot(kind='bar', rot=1)
>>> for p in ax.patches:
        ax.annotate(str(p.get_height()) + ' %', (p.get_x() * 1.005, p.get_height() * 1.005))
>>> ax.figure

输出:

enter image description here

相关问题 更多 >