ömer sarı ömer sarı - 3 months ago 12
Python Question

Matplot Legend uncorrect names

l have a 41_year_dataset and l would like to plot these data with Matplotlib and when l add legend on graph and legend shows 6 lines correctly except names. how can l fix it?

here is my code:

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()


example data:

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


another question is how l can get year column as x axis?. could not do this and l use for loop instead of it.enter image description herel

Answer

A simple trick is to call plot once per line, each with its own label argument containing the text that will show up in the legend.

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()

Now, when calling legend(), it will display the correct texts as you want.

enter image description here