python - 如何自定义条形注释以不显示所选值
问题描述
我有以下数据集:
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
- 在
pandas 1.3.4
、python 3.8.12
1.和matplotlib 3.4.3
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()
推荐阅读
- javascript - 为什么“this”不等于调用函数的对象?
- c++ - 使用多个sampler2D一次使用一个发送多个纹理?
- html - CSS 弹性盒 | 修复 Flex 列高度之间的空间
- file - 无法在 codeigniter 中显示文件验证错误消息
- python - 从 axios 传输到 django 的文件大小发生变化
- java - 仅显示数组中的唯一项
- bash - join 命令将匹配字段作为新行插入,如何为每个匹配生成单行?
- bash - 在 Bash 中,当它已经被重定向时如何打印到标准输出?
- java - 如何将 groupingBy 放入 Map 并更改键类型
- opcode - z80 的操作码布局有什么模式吗?