简体   繁体   中英

How to create a legend for a seaborn lineplot with two separately calculated lines

I have the following lineplot and I need to create a legend for the two lines. My problem is that I can't figure out how to use legend() with the two lines.

What I would like is having the legend box outside the graph with the "revenue" for the rvn line and "budget" for the bgt line.

I have tried

plt.legend(handles=[bgt, rvn])

and

plt.legend((bgt, rvn), ('Budget', 'Revenue')) ,

but they didn't work.

bgt = sns.lineplot(x= 'release_year', y='budget_adj_avg', data= df_bpr_avg) # blue
rvn = sns.lineplot(x= 'release_year', y='revenue_adj_avg', data= df_bpr_avg);# orange
plt.xlabel("Release year")
plt.ylabel("Amount ($)")
plt.title("Comparison average movies Budget and Revenue per year")
#plt.legend((bgt, rvn), ('Budget', 'Revenue'))
plt.legend(handles=[bgt, rvn])
plt.show()

Try this:

bgt = sns.lineplot(x= 'release_year', y='budget_adj_avg', data= df_bpr_avg, palette = 'blue', label = 'bgt') 
rvn = sns.lineplot(x= 'release_year', y='revenue_adj_avg', data= df_bpr_avg, palette = 'orange', label = 'rvn')
plt.xlabel("Release year")
plt.ylabel("Amount ($)")
plt.title("Comparison average movies Budget and Revenue per year")
plt.legend()
plt.show()

I don't have your data, so I tried with a data of my own:

    index   size    half
0   0   20          10
1   1   28          14
2   2   38          19
3   3   42          21
4   4   42          21
5   5   42          21
6   6   44          22
7   7   124         62
8   8   176         88
9   9   192         96
10  10  194         97
11  11  216         108
12  12  228         114
13  13  316         158
14  14  318         159
15  15  2048        1024
16  16  2714        1357
17  17  2802        1401
18  18  4128        2064
19  19  4186        2093
20  20  6910        3455
21  21  9313        4656
22  22  10816       5408
23  23  16560       8280
24  24  20704       10352
25  25  34766       17383
26  26  91022       45511

And I did

sns.lineplot(x = s['index'], y = s['size'], palette = 'blue', label="full")
sns.lineplot(x = s['index'], y = s['half'], palette = 'orange', label="half")
plt.legend()

and it gives me:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM