Matplot Legend不正确的名字

时间:2016-09-10 15:17:31

标签: python pandas matplotlib

我有一个41_year_dataset,我想用Matplotlib绘制这些数据,当我在图表上添加图例时,图例正确地显示6行,但名称除外。怎么能解决它?

这是我的代码:

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

filename="output813b.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()
y1=ts.pcp1
y2=ts.pcp2
y3=ts.pcp3
y4=ts.pcp4
y5=ts.pcp5
y6=ts.pcp6

"""print(yy.mean())"""
yr=1978
x=[]
for i in range(len(y1)):
    yr+=1
    x.append(yr)

plt.plot(x,y1,"ro",x,y2,x,y3,x,y4,x,y5,x,y6)
plt.ylabel('PCP SUM(mm)')
plt.xlabel("Years")
plt.title("SUM OF PCP")
plt.legend()
plt.show()

示例数据:

month   day     pcp1      pcp2      pcp3     pcp4     pcp5      pcp6
year                                                                      
1979   2382  5738  301.324   388.796   742.131  488.490  320.556   356.847
1980   2384  5767  294.930   423.243   823.397  552.660  376.599   453.105
1981   2382  5738  610.289   767.643  1277.867  859.655  663.417   726.007
1982   2382  5738  142.187   233.438   472.786  247.644  141.886   180.665
1983   2382  5738  322.897   423.026   824.202  541.882  312.711   339.395
1984   2384  5767  247.387   302.478   528.636  402.985  239.666   222.452
1985   2382  5738  277.279   375.935   778.349  417.070  238.995   289.696
1986   2382  5738  225.559   270.099   577.484  361.182  187.847   206.059
1987   2382  5738  377.751   510.545   952.429  664.123  451.063   510.339
1988   2384  5767  290.310   409.777   871.704  539.924  289.630   339.593

另一个问题是我如何将年份列作为x轴?无法做到这一点,我使用for循环代替它。enter image description here l

1 个答案:

答案 0 :(得分:1)

一个简单的技巧是每行调用一次plot,每个都有自己的label参数,其中包含将在图例中显示的文本。

plt.plot(x, y1, "ro", label='pcp1')
plt.plot(x, y2, label='pcp2')
plt.plot(x, y3, label='pcp3')
plt.plot(x, y4, label='pcp4')
plt.plot(x, y5, label='pcp5')
plt.plot(x, y6, label='pcp6')
plt.ylabel('PCP SUM(mm)')
plt.xlabel("Years")
plt.title("SUM OF PCP")
plt.legend()
plt.show()

现在,在调用legend()时,它会根据需要显示正确的文本。

enter image description here