Python图 - 我修复了这段代码,但需要有人解释它是如何工作的

时间:2014-08-20 15:41:20

标签: python matplotlib

我有以下python代码:

def graph(seconds,now, dayold, threedayold,weekold):
    x = np.arange(len(seconds))
    ynow = np.array(now)
    yday = np.array(dayold)
    y3day = np.array(threedayold)
    yweek = np.array(weekold)
    # y2 should go on top, so shift them up
    plt.plot(x,ynow)
    plt.plot(x,yday)
    plt.plot(x,y3day,'purple')
    plt.plot(x,yweek)
    plt.fill_between(x,ynow,yday,color='lightblue')
    plt.fill_between(x,yday,y3day,color='green')
    plt.fill_between(x,y3day,yweek,color='purple')
    plt.fill_between(x,yweek,0,color='red')
    plt.show()

生成此图表:

enter image description here

然而,'秒'是非继续结果列表,我真正想要的是:

def graph(seconds,now, dayold, threedayold,weekold):
    x = np.array(seconds)
    ynow = np.array(now)
    yday = np.array(dayold)
    y3day = np.array(threedayold)
    yweek = np.array(weekold)
    # y2 should go on top, so shift them up
    plt.plot(x,ynow)
    plt.plot(x,yday)
    plt.plot(x,y3day,'purple')
    plt.plot(x,yweek)
    plt.fill_between(x,ynow,yday,color='lightblue')
    plt.fill_between(x,yday,y3day,color='green')
    plt.fill_between(x,y3day,yweek,color='purple')
    plt.fill_between(x,yweek,0,color='red')
    plt.show()

这样我就能得到一个合适的X-Y情节。但是,当我尝试第二位代码时,我得到了这个错误:

josephs-mbp-3$Traceback (most recent call last):
  File "./temp.py", line 47, in <module>
    graph(a[0],a[1],a[2],a[3],a[4])
  File "./temp.py", line 41, in graph
    plt.fill_between(x,yweek,0,color='red')
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/pyplot.py", line 2287, in fill_between
    ret = ax.fill_between(x, y1, y2, where, interpolate, **kwargs)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/axes.py", line 6489, in fill_between
    y2 = np.ones_like(x)*y2
NotImplementedError: Not implemented for this type

任何人都可以告诉我是什么导致了这个以及我如何修复它?

编辑:啊哈!我修好了,但是想有人告诉我怎么做......

更改

 plt.fill_between(x,yweek,0,color='red')

plt.fill_between(x,yweek,[0]* len(seconds),color='red')

产生了我想要的 - 我能理解为什么这会是一个问题,但我很困惑为什么第一个版本可以工作......任何想法?

1 个答案:

答案 0 :(得分:1)

我认为秒可能是一个数字字符串列表,可能是从文件中加载而不是数字类型列表。

matplotlib的fill_between函数需要一个数值类型的数组作为参数,否则它会崩溃。这有点令人困惑,因为当你调用它时,绘图函数似乎会从字符串转换为浮动。

所以我觉得做的事情是:

x = [float(i) for i in seconds]

而不是:

x = np.array(seconds)

应该解决你的问题!