2016-10-20 57 views
0

我想在我的图表上添加一个表格,但是我不断收到错误。 这里是我的代码:表格标签的长度必须是错误的

import numpy as np 
import pandas as pd 
import csv 
import matplotlib.pyplot as plt 


filename="outputpcpb.csv" 
cols = ["date","year","month","day" ,"pcp1","pcp2","pcp3","pcp4","pcp5","pcp6"] 
data1=pd.read_csv(filename,sep=',') 
colmns_needed=["year","month" ,"pcp1","pcp2","pcp3","pcp4","pcp5","pcp6"] 

data2=pd.read_csv(filename,sep=',') 
data2.loc[:, 'pcp1':'pcp6'] = data2.loc[:, 'pcp1':'pcp6'].astype('float') 
yy=data2.groupby("year") 
mm=data2.groupby("month") 
ts=yy.sum() 
tm=mm.sum()/40 
tk=mm.std() 
krm=[float("{0:.2f}".format(i)) for i in tk.pcp1] 
krd=[float("{0:.2f}".format(x)) for x in ts.pcp1] 

print(krm,krd) 

y1=ts.pcp1;y11=tm.pcp1;y21=tk.pcp1 
y2=ts.pcp2;y12=tm.pcp2;y22=tk.pcp2 
y3=ts.pcp3;y13=tm.pcp3;y23=tk.pcp3 
y4=ts.pcp4;y14=tm.pcp4;y24=tk.pcp4 
y5=ts.pcp5;y15=tm.pcp5;y25=tk.pcp5 
y6=ts.pcp6;y16=tm.pcp6;y26=tk.pcp6 

yr=1978 
x=[] 
x1=[1,2,3,4,5,6,7,8,9,10,11,12] 
for i in range(len(y1)): 
    yr+=1 
    x.append(yr) 


fig3=plt.figure(3) 
axx2=fig3.add_subplot(111) 
axx2.set_axis_bgcolor("black") 
axx2.autoscale_view() 
axx2.plot(x1, y21,label='pcp1') 
axx2.plot(x1, y22,label='pcp2') 
axx2.plot(x1, y23,label='pcp3') 
axx2.plot(x1, y24,label='pcp4') 
axx2.plot(x1, y25,label='pcp5') 
axx2.plot(x1, y26,label='pcp6') 
axx2.set_ylabel('PCP std(mm)') 
axx2.set_xlabel("Month" ) 
axx2.set_title("STD OF PCP") 

plt.table(cellText=[[krm[0],krd[0]],[krm[1],krd[1]],[krm[2],krd[2]],[krm[3],krd[3]],[krm[4],krd[4]],[krm[5],krd[5]],[krm[6],krd[6]],[krm[7],krd[7]],[krm[8],krd[8]],[krm[9],krd[9]],[krm[10],krd[10]],[krm[11],krd[11]]], 
      rowLabels = ['STD OF PCP1', 'SUM PF PCP1'], 
      colLabels=["JAN","FEB","MAR","APR","MAY","JUN","JULY","AUG","SEPT","OCT","NOV","DEC"], 
      loc="bottom", 
      bbox=[0,-0.2,1,0.15]) 


plt.grid(True) 
plt.legend() 
plt.legend(loc="lower left") 

plt.show() 

当我运行的代码,我得到这个错误:

raise ValueError("'rowLabels' must be of length {0}".format(rows)) 
    ValueError: 'rowLabels' must be of length 12 

我有2行,我不明白这是什么错误与“长12”的意思。我该如何解决这个问题?

+0

只要把行标签10个空字符串... –

+0

这意味着额外的10个多行,我不希望看到的空行。我会试着看到结果 –

+0

我只是说把它放在那里让错误消失。有可能是另一种方式,也许 –

回答

2

您以错误的方式格式化了cellText。如果您打印:

print len(cellText)  # = 12 (no. of rows) 
print len(cellText[0]) # = 2 (no. of cols) 

即,目前它有12行2列,而不是2行12列。

要获得12列和2行,你需要一个长度为2数组,其长度与子阵12

即是这样的:

cellText=[krm,krd] 

我们可以检查这样的:

print len(cellText)  # = 2 (no. of rows) 
print len(cellText[0]) # = 12 (no. of cols) 

来源:你可以看到如何matplotlib转换cellText进入matplotlib/table.py这里的行和列的代码,就行593:https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/table.py#L593

+0

非常感谢 –

相关问题