如何自定义条形图批注以不显示选定的值 [英] How to customize bar annotations to not show selected values

查看:95
本文介绍了如何自定义条形图批注以不显示选定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据集:

data = [6.92, 1.78, 0.0, 0.0, 3.5, 8.82, 3.06, 0.0, 0.0, 5.54, -10.8, -6.03, 0.0, 0.0, -6.8, 13.69, 8.61, 9.98, 0.0, 9.42, 4.91, 3.54, 2.62, 5.65, 1.95, 8.91, 11.46, 5.31, 6.93, 6.42]

是否有方法从条形图中删除0.0标签?

我尝试df = df.replace(0, ""),但收到list index out of range错误代码。

我的代码:

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

data = [6.92, 1.78, 0.0, 0.0, 3.5, 8.82, 3.06, 0.0, 0.0, 5.54, -10.8, -6.03, 0.0, 0.0, -6.8, 13.69, 8.61, 9.98, 0.0, 9.42, 4.91, 3.54, 2.62, 5.65, 1.95, 8.91, 11.46, 5.31, 6.93, 6.42]

df = pd.DataFrame(np.array(data).reshape(6,5), columns=['Bank1', 'Bank2', 'Bank3', 'Bank4', 'Bank5'], index =['2016', '2017', '2018', '2019', '2020', '2021'])

print(df)
ax = df.plot(kind='bar', rot=0, xlabel='Year', ylabel='Total Return %', title='Overall Performance', figsize=(15, 10))

ax.bar_label(ax.containers[0], fmt='%.1f', fontsize=8, padding=3)
ax.bar_label(ax.containers[1], fmt='%.1f', fontsize=8, padding=3)
ax.bar_label(ax.containers[2], fmt='%.1f', fontsize=8, padding=3)
ax.bar_label(ax.containers[3], fmt='%.1f', fontsize=8, padding=3)
ax.bar_label(ax.containers[4], fmt='%.1f', fontsize=8, padding=3)

ax.legend(title='Columns', bbox_to_anchor=(1, 1.02), loc='upper left')
plt.show()

推荐答案

  • labels传递给matplotlib.pyplot.bar_label必须是自定义的
    • 根据需要调整比较(!= 0)值或范围。
  • labels = [f'{v.get_height():0.0f}' if v.get_height() != 0 else '' for v in c ]不带赋值表达式(:=)。
  • 有关使用.bar_label.bar_label
  • 的其他详细信息和示例,请参阅此answer
  • 测试于pandas 1.3.4python 3.8.121.matplotlib 3.4.31.
    1. 要求的最低版本分别为3.8和3.4.2
import pandas as pd
import matplotlib.pyplot as plt

data = [6.92, 1.78, 0.0, 0.0, 3.5, 8.82, 3.06, 0.0, 0.0, 5.54, -10.8, -6.03, 0.0, 0.0, -6.8, 13.69, 8.61, 9.98, 0.0, 9.42, 4.91, 3.54, 2.62, 5.65, 1.95, 8.91, 11.46, 5.31, 6.93, 6.42]

df = pd.DataFrame(np.array(data).reshape(6,5), columns=['Bank1', 'Bank2', 'Bank3', 'Bank4', 'Bank5'], index =['2016', '2017', '2018', '2019', '2020', '2021'])

ax = df.plot(kind='bar', rot=0, xlabel='Year', ylabel='Total Return %', title='Overall Performance', figsize=(15, 10))

for c in ax.containers:
    
    # customize the label to account for cases when there might not be a bar section
    labels = [f'{h:0.1f}' if (h := v.get_height()) != 0 else '' for v in c ]
    
    # set the bar label
    ax.bar_label(c, labels=labels, fontsize=8, padding=3)

ax.legend(title='Columns', bbox_to_anchor=(1, 1.02), loc='upper left')
plt.show()

这篇关于如何自定义条形图批注以不显示选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆