You can look at the matplotlib documentation, which isn’t too bad, but this might also be helpful.

import pandas as pd
import matplotlib.pyplot as plt

%matplotlib inline
df = pd.read_csv("classwork/countries.csv")
df.head(3)
country continent gdp_per_capita life_expectancy population
0 Afghanistan Asia 663 54.863 22856302
1 Albania Europe 4195 74.200 3071856
2 Algeria Africa 5098 68.963 30533827

Plotting

Ignore the fact that this is a really dumb plot of nothing.

df.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x10e2db4e0>

png

Removing the legend

ax = df.plot()
ax.legend_.remove()

png

Moving the legend

loc=… * 'best' * 'upper right' * 'upper left' * 'lower left' * 'lower right' * 'right' * 'center left' * 'center right' * 'lower center' * 'upper center' * 'center'

ax = df.plot()
ax.legend(loc='lower right')
<matplotlib.legend.Legend at 0x10e2446a0>

png

ax = df.plot()
ax.legend(loc='center left')
<matplotlib.legend.Legend at 0x10f0ae9e8>

png

Changing the title of the legend

ax = df.plot()
ax.legend(title='This is a legend')
<matplotlib.legend.Legend at 0x10f269cc0>

png

Making it not so busy and complex and shadow-y etc

You can also use an rcParams with a legend.frameon value of False

ax = df.plot()
ax.legend(frameon=False)
<matplotlib.legend.Legend at 0x10f8344a8>

png

Make it horizontal instead of vertical

ax = df.plot()
ax.legend(ncol=5, loc='upper center')
<matplotlib.legend.Legend at 0x10fc0a710>

png

Push it outside

# bbox_to_anchor=(0.5, 1)
# 50% of the way left -> right
# 100% of the way bottom -> top
ax = df.plot()
ax.legend(ncol=5, 
          loc='upper center',
          bbox_to_anchor=(0.5, 1.0),
          bbox_transform=plt.gcf().transFigure)
<matplotlib.legend.Legend at 0x110458c50>

png

# bbox_to_anchor=(1.2, 0.5)
# 120% of the way left -> right
# 50% of the way bottom -> top
ax = df.plot()
ax.legend(loc='lower right',
          bbox_to_anchor=(1.2, 0.5),
          bbox_transform=plt.gcf().transFigure)
<matplotlib.legend.Legend at 0x110efe2b0>

png

Other options?

Run ax.legend? to see a lot lot lot more.