【问题标题】:Issue with multiple loops to create plots, getting error多个循环创建绘图的问题,出现错误
【发布时间】:2014-07-24 07:20:25
【问题描述】:

基本上我一直在尝试从数据框创建图。首先,我定义数据框(glist),然后定义 y 值(alist)以针对日期进行绘图。它们都单独工作,但不在此循环中。有什么建议吗?

编辑:现在的问题是,当我调用它们时,第一个情节正在为所有其他情节重新绘制。我曾尝试在循环开始时使用 plt.clr() 但似乎不起作用。

x,y,= (0.5,-.16)
fmt = DateFormatter('%m/%d/%Y')
nlist=[]
def plots():

Totrigs,TotOrDV,TotOrH,TotGas,TotOil,TotBit,ABFl,ABOr,SKFl,SKOr,BCOr,MBFl,MBOr = dataforgraphs()
glist = [Totrigs,ABFl,ABOr,SKFl,SKOr,BCOr,MBFl,MBOr]
alist = [['Total Rigs'],['GAS','OIL','BIT'],[['HZ','DIR/VERT']],[['GAS','OIL']],[['HZ','DIR/VERT']],['OIL'],[['HZ','DIR/VERT']],[['HZ','DIR/VERT']]]

for i,k in zip(glist,alist):
    fig = i.plot(y=k,linewidth=2.0, legend=False)
    fig.patch.set_facecolor('#EEECE1')
    fig.xaxis.set_major_formatter(fmt)
    fig.legend(loc= 'upper center',bbox_to_anchor=(x,y),fancybox=True)
    nlist.append(fig)

    return (nlist)

def Totgraph():
nlist = plots()
Totrigs = nlist[0]           
plt.savefig('C:\\Python33\\XcelFiles\\Pics\\Totrigs.png',bbox_inches='tight')
plt.clf()

def ABFLgraph():
nlist = plots()
ABFl = nlist[1]
plt.title('Alberta Fluid Type')
plt.savefig('C:\\Python33\\XcelFiles\\Pics\\ABFl.png',bbox_inches='tight')

【问题讨论】:

  • 你在哪一行得到错误?
  • 我在想fig = i.plot(y=alist[x],sharex=True, linewidth=2.0, legend=False) 是你的问题。在这种情况下,您的 y = alist[x] 是一个列表。我认为 y 不能是一个列表,这就是它给你这个错误的原因。
  • 我应该把 alist 变成什么以便它读取它作为 y 值的列标签?
  • @Elias DataFrame 上的 plot 方法采用参数列表(同样 sharex 默认为 True)。没有更多信息,很难回答。错误在哪一行? yfmt 是什么?您所有的DataFrames 是否都具有相同的列和类型?为什么要使用x 索引而不是直接使用k
  • 哪个错误? ValueError?因为那不是有效的语法,但也不是您的代码中的...

标签: python loops matplotlib pandas


【解决方案1】:

样本数据:

import pandas as pd
df = pd.DataFrame({'x':[1,2,3,4], 'y':[10,20,30,40], 'z':[100,200,300,400]})

d_list = [df, df, df, df]
y_list = [['z'], ['y'], ['y', 'z']]

你的代码应该是这样的:

x,y,= (0.5,-.16)
fmt = DateFormatter('%m/%d/%Y')
res = []
for g in glist:
    for a in alist:
        fig = g.plot(x='x', y=a, sharex=True, linewidth=2.0, legend=False))
        fig.patch.set_facecolor('#EEECE1')
        # my x axis isn't dates, but you get the picture...
        # fig.xaxis.set_major_formatter(fmt)
        fig.legend(loc= 'upper center',bbox_to_anchor=(x,y),fancybox=True)
        res.append(fig) 

您当前出错的代码:

for g, a in glist, alist:
    print g, a

不是有效的python。您需要像问题中的代码一样具有嵌套循环。或者你可以使用 zip 之类的东西来获取对:

for g, a in zip(glist, alist):
    print g, a

【讨论】:

  • The code you're erroring on currently: for d, y in d_list, y_list: print d, y我在他的代码中没有看到?
  • 压缩包成功了!!谢啦。基本上,问题是两者都需要同时通过循环读取,因为我创建了绘图,同时 k 拥有要使用的列。
  • 是的,如果他显示错误的实际行会很好。干得好
  • @Justin 出现转载错误。我想我知道它为什么会发生,但不知道如何解决它。我的尝试都是徒劳的。我编辑了原始帖子。
  • @carevans88 虽然我很了不起,但我不够直观,无法理解这一点。请恢复您的编辑,接受我上面的答案并提出一个新问题,如果需要,请链接到这个问题。确保包含所有相关信息,包括确切的错误。但是,在您的编辑中,plt 不存在。您需要引用返回的对象,例如Totrigs.savefig.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-25
相关资源
最近更新 更多