【问题标题】:Position of Matplotlib Pyplot bar chart labels not consistent with nan valuesMatplotlib Pyplot 条形图标签的位置与 nan 值不一致
【发布时间】:2016-08-22 05:58:59
【问题描述】:

我正在绘制包含缺失值 (np.nan) 的数据条形图。似乎当 np.nan 值出现在最后一个类别中时,x 轴刻度的位置与没有 np.nans 或 NaN 值位于不同位置时的位置不同。

import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline

years = np.array([2011, 2012, 2013, 2014, 2015])
x = np.arange(len(years))
y1 = np.array([ 29.,  10.,  16.,  29., np.nan])
y2 = np.array([ 29.,  10.,  np.nan,  29., 16.])
y3 = np.array([ np.nan,  29., 29.,  10.,  16.])

f = plt.figure(figsize=(4,6))

ax = f.add_subplot(311)
ax.bar(x, y1, align='center')
ax.set_xticks(x)
ax.set_xticklabels(years)

ax = f.add_subplot(312)
ax.bar(x, y2, align='center')
ax.set_xticks(x)
ax.set_xticklabels(years)

ax = f.add_subplot(313)
ax.bar(x, y3, align='center')
ax.set_xticks(x)
ax.set_xticklabels(years)

plt.show()

理想情况下,我希望 x 轴标签位于同一个位置,无论数据中是否存在 NaN 值。

【问题讨论】:

    标签: python matplotlib bar-chart axis-labels


    【解决方案1】:

    如果您需要绘图上的特定范围,您可以明确设置它。在每个块添加之后,例如

    ax.set_xlim(-0.5, years.size - 0.5)
    

    【讨论】:

      【解决方案2】:

      我找到了一个解决方案:

      将 y1、y2、y3 数组替换为 np.nan_to_num(y1) ...等

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-08
        • 1970-01-01
        • 1970-01-01
        • 2012-03-15
        • 1970-01-01
        • 2015-05-09
        相关资源
        最近更新 更多