user11812290
user11812290

Reputation:

Plotting legend with a for loop matplotlib

I am trying to plot a multiple lines with a for loop, but I want to create an individual legend for each line. Each line represents a location like 'Labrador sea', etc. but when I try to plot the legends for each line, only the first one "labrador sea" is visible How do I make matplotlib plot for each line a legend, which has a customizable label?

This is the code I have so far:

fig,ax=plt.subplots()

lines = []

for i in [26,27,28,39,30,32,84,86,87,88,96,98,99]:
    lines = ax.plot(years, mov_ave(fwf_tot.where(ds.ocean_basins == i).resample(TIME='1AS').sum().sum(dim=('X','Y')),5,'edges'))

#plt.title('Total FWF anomalies per ocean basin (moving average)')
ax.legend(lines[:13], ['Labrador sea','Hudson strait','Davis strait','Baffin bay', 'Lincoln sea', 'Irish sea and St. George', 'Arctic ocean', 'Barentsz sea', 'Greenland sea',
      'North sea', 'Kategat', 'Skagerrak', 'Norwegian sea'],loc='upper left');
plt.grid()
plt.show()

enter image description here

Upvotes: 1

Views: 1171

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

You are redefining lines after each plot. Maybe you want:

lines = []

for i in [26,27,28,39,30,32,84,86,87,88,96,98,99]:
    line = ax.plot(years, mov_ave(fwf_tot.where(ds.ocean_basins == i).resample(TIME='1AS').sum().sum(dim=('X','Y')),5,'edges'))
    # add the line to line list
    lines.append(line)

ax.legend(lines, ....)

However, I think it's cleaner to pass the label to ax.plot:

labels = ['Labrador sea','Hudson strait','Davis strait','Baffin bay', 'Lincoln sea', 'Irish sea and St. George', 'Arctic ocean', 'Barentsz sea', 'Greenland sea',
      'North sea', 'Kategat', 'Skagerrak', 'Norwegian sea']

values = [26,27,28,39,30,32,84,86,87,88,96,98,99]
for i,l in zip(values, labels):
    lines = ax.plot(years, mov_ave(fwf_tot.where(ds.ocean_basins == i)
                                          .resample(TIME='1AS').sum()
                                          .sum(dim=('X','Y')),
                                   5,'edges'),
                    label=l)

plt.title('Total FWF anomalies per ocean basin (moving average)')

ax.legend()
plt.grid()
plt.show()

Upvotes: 1

Related Questions