【问题标题】:Argument dimensions are incompatible, issue with filling_between参数尺寸不兼容,fill_between 有问题
【发布时间】:2017-03-20 15:26:53
【问题描述】:

我在图表中绘制 2 条线,我想在中间的区域加阴影,但是我无法做到,我的数据是 2 个 DataFrames,有 365 个观察值。 我目前的代码是这样的。

plt.figure()
plt.plot(minimos, '', maximos, '')
plt.scatter(df6x, df6, s=50, c='r', alpha=0.8)
plt.scatter(df5x, df5, s=50, c='b', alpha=0.8)
plt.legend(['High', 'Low'])

我有这个:

有关 DataFrame 的更多信息

  print(type(maximos),type(minimos), type(x))
  print(maximos.shape, minimos.shape,x.shape)

<class 'numpy.ndarray'> <class 'numpy.ndarray'> <class 'numpy.ndarray'>
 (365, 1) (365, 1) (365, 1)  

但我仍然遇到 ValueError 的问题:参数维度不兼容

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

 maximos = maximos.values
 minimos = minimos.values
 x = np.arange(0,365,1)
 x = x.reshape(365,1)
 fig = plt.figure()
 plt.plot(x, maximos, c='r', alpha=0.8)
 plt.plot(x, minimos, c='b', alpha=0.8)
 # fill between hgh and low
 ax = fig.gca()
 ax.fill_between(x, minimos, maximos, facecolor='purple')
 plt.legend(['High', 'Low'])
 plt.scatter(df6x, df6, s=50, c='r', alpha=0.8)
 plt.scatter(df5x, df5, s=50, c='b', alpha=0.8)

错误在这行代码 ax.fill_between(x, minimos, maximos, facecolor='purple')。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    这里没有理由使用x = x.reshape(365,1)。正如错误所说,重塑 x 会使参数尺寸不兼容。省略该行将使代码正常工作:

    import numpy as np; np.random.seed(42)
    import matplotlib.pyplot as plt
    
    maximos = np.cumsum(np.random.rand(365)-0.5)+40
    minimos = np.cumsum(np.random.rand(365)-0.5)+0.7
    
    x = np.arange(0,365,1)
    
    fig = plt.figure()
    plt.plot(x, maximos, c='r', alpha=0.8)
    plt.plot(x, minimos, c='b', alpha=0.8)
    
    plt.fill_between(x, minimos, maximos, facecolor='purple')
    plt.legend(['High', 'Low'])
    
    plt.show()
    

    【讨论】:

    • 没有重塑我得到了这个, (365, 1) (365, 1) (365,)我仍然无法使其工作
    • 您现在仍需要将两个数组 minimos 和 maximos 重塑为只有 1 个维度。
    【解决方案2】:

    使用fill_betweenhttp://matplotlib.org/examples/pylab_examples/fill_between_demo.html

    import matplotlib.pylab as plt
    import numpy as np
    
    x = np.arange(1,365,1)
    hgh = np.random.uniform(20,30,len(x))
    low = np.random.uniform(-10,10, len(x))
    
    fig = plt.figure()
    plt.plot(x, hgh, c='r', alpha=0.8)
    plt.plot(x, low, c='b', alpha=0.8)
    
    # fill between hgh and low
    ax = fig.gca()
    ax.fill_between(x, low, hgh, facecolor='gold')
    
    plt.legend(['High', 'Low'])
    plt.show()
    

    【讨论】:

    • 这似乎没问题,但我无法让它工作我得到一个 ValueError:参数尺寸不兼容,知道为什么我会得到这个吗?
    • 可能是两个数据框不共享同一个索引。最佳解决方案将取决于数据,因此共享有关数据帧的更多信息会有所帮助。在任何情况下,共享产生错误的代码对于帮助您都是必要的。
    • 我添加了有关 DataFrames 的更多信息,我可以添加更多信息吗?
    猜你喜欢
    • 2013-08-21
    • 2021-06-11
    • 2016-08-21
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多