【问题标题】:Misplaced position of value counts on top of bar graph in pythonpython中条形图顶部的值计数位置错误
【发布时间】:2021-12-05 07:21:22
【问题描述】:

我使用代码计算了数据框中的缺失值:

per_B = df.isna().mean().round(4) * 100

并使用以下代码绘制,顶部是 NaN 值计数,但最后两个值计数位置放错了位置。

f, ax = plt.subplots(figsize=(20, 15))
for i,item in enumerate(zip(per_B.keys(), per_B.values)):
    if (item[1] > 0):
        ax.bar(item[0], item[1], label = item[0])
        ax.text(i - 0.40, item[1] + 0.5 , str(np.round(item[1],2)))    
ax.set_xticklabels([]) 
ax.set_xticks([]) 
plt.title('NaN Value percentage in Training Set B')
plt.ylim(0,115)
plt.ylabel('Percentage')
plt.xlabel('Columns')
plt.legend(loc='upper left')
plt.show()

由于最后两列的值计数放错了位置,有人可以帮我解决代码中的问题吗?

【问题讨论】:

  • 作为调试的方式,索引值和标签值是否存在一一对应关系? print(i)print(np.round(item[1],2))
  • 是的,但是我知道为什么最后 2 个标签放错了位置?或者,如果您知道将 NaN 百分比绘制为条形图的其他方式(代码)?那太好了……
  • 当然,还有最重要的价值。

标签: python matplotlib seaborn nan


【解决方案1】:

文本放错位置的原因是,即使您没有绘制条形图,您也让i 增加(在结束之前似乎有两个带有item[1] <= 0 的“项目”)。您可以通过将i 放在for 之外并仅在绘制条形时增加它来解决此问题。

所以,类似:

i = 0
for key, value in zip(per_B.keys(), per_B.values)):
    if (value > 0):
        ax.bar(key, value, label=key)
        ax.text(i, value + 0.5, str(np.round(value, 2)), ha='center')
        i = i + 1 # increment the counter

可以使用bar_label() 函数(matplotlib 3.4 中的新功能)简化代码,也可以通过创建仅包含非零元素的per_B 子集:

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

# first create some test data
data = np.random.rand(1000)
data[np.random.randint(0, 1000, 2000)] = np.nan
df = pd.DataFrame(data.reshape(-1, 10), columns=[*'abcdefghij'])
df['g'] = 1 # no NaNs in columns 'g' and 'h'
df['h'] = 1

per_B = df.isna().mean().round(4) * 100

per_B_nonzeo = per_B[per_B > 0] # subset containing all the nonzero vlaues

fig, ax = plt.subplots()
for key, value in per_B_nonzeo.iteritems():
    bar = ax.bar(key, value, label=key)
    ax.bar_label(bar, labels=[f'{value:.2f}'])
plt.show()

【讨论】:

  • AttributeError: 'AxesSubplot' object has no attribute 'bar_label'
  • @Huzaifa 您需要升级 matplotlib,因为 bar_label 是自 3.4 版以来的新功能。对于较旧的 matplotlib 版本,您仍然可以使用帖子第一部分中的代码。
  • 好的。我在 AWS 上使用 Jupyter Lab,当我尝试更新 matplotlib 时,它说安装了最新版本,但那是旧版本。
猜你喜欢
  • 2017-03-25
  • 1970-01-01
  • 2017-06-28
  • 2017-07-29
  • 2014-09-21
  • 2019-08-01
  • 2022-07-06
  • 1970-01-01
  • 2021-05-22
相关资源
最近更新 更多