【问题标题】:How to suppress zero in stacked bar graph display如何在堆积条形图显示中抑制零
【发布时间】:2020-01-10 15:56:16
【问题描述】:

我有一个如下的示例堆叠条形字符。如何在图表中抑制“0”值

无论哪里有 0,我都不想显示这些值。有什么办法可以抑制零

我在显示数据时有以下代码

for xpos, ypos, yval in zip(TABLE_NAMES, ID1/2, ID1):
    plt.text(xpos, ypos, yval, ha="center", va="center",fontsize=20)
for xpos, ypos, yval in zip(TABLE_NAMES, ID1+ID2/2, ID2):
    plt.text(xpos, ypos, yval, ha="center", va="center",fontsize=20)

我尝试了以下方法

ID1[ID1 == 0] = np.nan ( to pass nan value but i am getting error 
Error: ValueError: cannot convert float NaN to integer

有什么办法可以实现

以及如何使 y 轴根据数据显示(根据下图,我在 Y 轴上最多有 6 个。我为此使用 np.arange

np.arange(0,6,1) 

但在未来 i 可能有不同的值大于 100 。如果不指定任何函数,如 np.arange,有什么方法可以动态传递它来处理没有任何范围的 yaxis ..?

【问题讨论】:

    标签: python numpy matplotlib stacked-chart


    【解决方案1】:

    由于矩形补丁已经生成,我们可以从图中获取高度和宽度并根据这些添加文本:

    In [164]: df
    Out[164]: 
              a         b         c         d
    0  0.807540  0.719843  0.291329  0.928670
    1  0.449082  0.000000  0.575919  0.299698
    2  0.703734  0.626004  0.582303  0.243273
    3  0.363013  0.539557  0.000000  0.743613
    4  0.185610  0.526161  0.795284  0.929223
    5  0.000000  0.323683  0.966577  0.259640
    6  0.000000  0.386281  0.000000  0.000000
    7  0.500604  0.131910  0.413131  0.936908
    8  0.992779  0.672049  0.108021  0.558684
    9  0.797385  0.199847  0.329550  0.605690
    
    In [165]:
    from matplotlib.patches import Rectangle
    df.plot.bar(stacked=True)
    ax = plt.gca()
    for p in ax.get_children()[:-1]:  # skip the last patch as it is the background
        if isinstance(p, Rectangle):
            x, y = p.get_xy()
            w, h = p.get_width(), p.get_height()
            if h > 0:  # anything that have a height of 0 will not be annotated
                ax.text(x + 0.5 * w, y + 0.5 * h, '%0.2f'%h, va='center', ha='center')
    plt.show()
    

    【讨论】:

    • 非常感谢您的回复。我得到小数的值让我们说 12 --> 12.00 有没有办法我可以删除那些小数部分并将其显示为 12
    • @Ravi,字符串格式由%0.2f部分控制,检查pyformat.info。如果那里只有整数,可以尝试最简单的%s
    • @非常感谢您的建议。我如何动态处理 y 轴以显示完整的最大值范围,有没有办法可以在图形的后端添加网格与一些特定的单词...?
    • 将所有y + h 追加到一个列表中并设置y 最大值(通过ylim)并将所述列表的最大值用作新的y 最大值
    • @我们可以在图表的后端添加徽标吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    相关资源
    最近更新 更多