gpt4 book ai didi

python - 如果值为 0,则隐藏 matplot 注释

转载 作者:行者123 更新时间:2023-12-01 08:20:26 26 4
gpt4 key购买 nike

这是 question 的后续内容。

看下面的例子:

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

d = {'group 1': [0, 2, 5, 7, 0, 5, 0],
'group 2': [0, 0, 1, 8, 2, 6, 2],
'group 3': [0, 0, 0, 4, 4, 8, 4]}
df = pd.DataFrame(d)

ax = df.plot.barh(stacked=True, figsize=(10,12))

for p in ax.patches:
left, bottom, width, height = p.get_bbox().bounds
ax.annotate(str(width), xy=(left+width/2, bottom+height/2),
ha='center', va='center', size = 12)

plt.legend(bbox_to_anchor=(0, -0.15), loc=3, prop={'size': 14}, frameon=False)

您可以看到注释(当值为 0 时)如何使图表看起来非常糟糕。

enter image description here

有人知道如何删除或隐藏 0 值的注释,同时保留非零值的注释吗?

最佳答案

我相信您只需要在循环中添加一个 if 语句

for p in ax.patches:
left, bottom, width, height = p.get_bbox().bounds
ax.annotate(str(width), xy=(left+width/2, bottom+height/2),
ha='center', va='center', size = 12)

过滤掉width == 0.0的实例,即

for p in ax.patches:
left, bottom, width, height = p.get_bbox().bounds
if width != 0.0:
ax.annotate(str(width), xy=(left+width/2, bottom+height/2),
ha='center', va='center', size = 12)

这会给你

Plot with annotations filtered (size adjusted from OP code)

关于python - 如果值为 0,则隐藏 matplot 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54682665/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com