【问题标题】:Missing values at the beginning - matplotlib开头缺失值 - matplotlib
【发布时间】:2016-11-26 09:26:18
【问题描述】:

尝试在我的 matplot 图中添加缺失值(无)或 numpy np.nan。通常这种方式可能会出现缺失值:

import matplotlib.pyplot as plt

fig = plt.figure(1)

x = range(10)
y = [1, 2, None, 0, 1, 2, 3, 3, 5, 10]

ax = fig.add_subplot(111)
ax.plot(x, y, 'ro')

plt.show()

但在图表的开头似乎不容易支持缺失值。

import matplotlib.pyplot as plt

fig = plt.figure(1)

x = range(10)
y = ([None]*5)+[x for x in range(5)]

ax = fig.add_subplot(111)
ax.plot(x, y, 'ro')

plt.show()

这显示:

但我想以x=0 而不是x=5 开头。 希望有一个简单的方法来解决这个问题。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    空值似乎对第二个图没有影响的原因是因为轴对象的 x 和 y 限制的自动确定。在第一种情况下,您拥有跨越您关心的整个 x / y 范围的“真实”数据,并且轴会自动缩放以适应该数据。在第二个示例中,您的真实数据仅涵盖 x 值的上限,因此 matplotlib 将截断 x 轴,因为没有可显示的内容。

    解决此问题的方法是明确指定坐标区的xlims。您可以使用x 的值来确定它们应该是什么。

    plt.xlim(x[0], x[-1])
    

    【讨论】:

      【解决方案2】:

      Matplotlib 自动选择 x 轴和 y 轴的参数。在这种情况下,它只显示可以可视化的点。如果 x- 或 y 为“无”,则无法显示任何内容。如果您还想查看图表的“空白”部分,只需自行调整轴范围。

      如何做到这一点,已在本论坛的类似问题中多次回答,例如:

      Matplotlib/pyplot: How to enforce axis range?

      Python, Matplotlib, subplot: How to set the axis range?

      setting y-axis limit in matplotlib

      还有更多。因此,我将避免重复本论坛其他地方已经说过的话。

      【讨论】:

        猜你喜欢
        • 2020-08-12
        • 2021-02-23
        • 2013-05-03
        • 2016-11-05
        • 1970-01-01
        • 1970-01-01
        • 2018-06-01
        • 1970-01-01
        • 2021-03-21
        相关资源
        最近更新 更多