表rowLabels必须是长度错误

时间:2016-10-20 11:28:39

标签: python matplotlib

我想在我的图表上添加一个表但是我一直收到错误。 这是我的代码:

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"。我如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

您已经错误地格式化了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