user13412850
user13412850

Reputation: 519

python - repositioning my legend using loc

this is the output of my code

enter image description here

as you can see both legends 'pl' and 'ppl' are overlapping at the top right. How do I get one of them to move to top left. I tried searching for ans, and used "loc" to fix the issue, somehow I continue getting error. Can someone help please?

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

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax1.set_xlabel('Date')
ax1.set_ylabel('percent change / 100')
dd = pd.DataFrame(np.random.randint(1,10,(30,2)),columns=['pl','ppl'])
dd['pl'].plot(ax=ax1,legend=True)
dd['ppl'].plot(ax=ax2, style=['g--', 'b--', 'r--'],legend=True)

ax2.set_ylabel('difference')
plt.show()

Upvotes: 1

Views: 78

Answers (3)

Pietro
Pietro

Reputation: 1110

You can create the legend in several ways:

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

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax1.set_xlabel("Date")
ax1.set_ylabel("percent change / 100")
dd = pd.DataFrame(np.random.randint(1, 10, (30, 2)), columns=["pl", "ppl"])
dd["pl"].plot(ax=ax1)
dd["ppl"].plot(ax=ax2, style=["g--", "b--", "r--"])

# # two separate legends
# ax1.legend()
# ax2.legend(loc="upper left")

# # a single legend for the whole fig
# fig.legend(loc="upper right")

# # a single legend for the axis
# get the lines in the axis
lines1 = ax1.lines
lines2 = ax2.lines
all_lines = lines1 + lines2
# get the label for each line
all_labels = [lin.get_label() for lin in all_lines]
# place the legend
ax1.legend(all_lines, all_labels, loc="upper left")

ax2.set_ylabel("difference")
plt.show()

The last one I left uncommented creates a single legend inside the ax, with both lines listed.

Cheers!

Upvotes: 1

azal
azal

Reputation: 1260

I think you need to call legend on plot and position the legend accordingly. Please see below.

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

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax1.set_xlabel('Date')
ax1.set_ylabel('percent change / 100')
dd = pd.DataFrame(np.random.randint(1,10,(30,2)),columns=['pl','ppl'])

dd['pl'].plot(ax=ax1, legend=True).legend(loc='center left',bbox_to_anchor=(1.0, 0.5))
dd['ppl'].plot(ax=ax2, style=['g--', 'b--', 'r--'],legend=True).legend(loc='upper right')

Upvotes: 1

BigBen
BigBen

Reputation: 50008

Perhaps plot directly with matplotlib instead of using DataFrame.plot:

ax1.plot(dd['pl'], label='pl')
ax1.legend(loc='upper left')
ax2.plot(dd['ppl'], ls='--', c='g', label='ppl')
ax2.legend(loc='upper right')

Output:

enter image description here

Upvotes: 2

Related Questions