python - 绘制带有条件的seaborn histplot bar_label

标签 python matplotlib formatting seaborn

我想绘制一个seaborn histogramlabels显示每个条形的值。我只想显示非零值,但我不知道该怎么做。我的 MWE 是

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

xlist = 900+200*np.random.randn(50,1)

fig, ax = plt.subplots()
y = sns.histplot(data=xlist, element="bars", bins=20, stat='count', legend=False)
y.set(xlabel='total time (ms)')
y.bar_label(y.containers[0])
## y.bar_label(y.containers[0][y.containers[0]!=0])
plt.show()

图表看起来像

enter image description here

我想删除所有 0标签。

最佳答案

更新

@BigBen 建议的最佳版本:

labels = [str(v) if v else '' for v in y.containers[0].datavalues]
y.bar_label(y.containers[0], labels=labels)

尝试:

labels = []
for p in y.patches:
    h = p.get_height()
    labels.append(str(h) if h else '')

y.bar_label(y.containers[0], labels=labels)

enter image description here

关于python - 绘制带有条件的seaborn histplot bar_label,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70673809/

相关文章:

python - 给定 4 个点,如何在 Python 中定义超平面?那么我如何定义 4 个超平面的交点(这应该是一个点)?

python - 使用matplotlib在单个pdf页面上保存多个图

linux - 将 bash/shell 脚本时间格式化为天、小时、分钟和秒

Java 2 列号格式

python - 如何创建和写入 textiowrapper 和 readlines

python - 为什么 AudioSegment 不读取 'mp3' ?

python - Python 闭包是否需要外部作用域超出作用域(即结束)

python - 在 python 中绘制轨道轨迹

python - 如何为按时间排序的 matplotlib 图序列制作动画

java - 为什么我的 Pascal 三角形程序没有提供正确的格式?