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

2024-04-26 10:13:51 发布

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

这是这个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值的注释,同时保留非零值的注释吗?你知道吗


Tags: importdfsizeasgrouppltaxwidth
1条回答
网友
1楼 · 发布于 2024-04-26 10:13:51

我相信您只需要在循环中添加一个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)

相关问题 更多 >