Search code examples
pythongraphsubplot

How to put legends in each plots


I am new learner of python and I'm having hard time to make a legend in each 4 graphs. I want to put each equation's formula in the legend. I cant think about more to make the legend on the graphs.

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

mpl.rcParams['lines.color'] = 'k'
mpl.rcParams['axes.prop_cycle'] = mpl.cycler('color', ['k'])

x = np.linspace(-9, 9, 400)
y = np.linspace(-5, 5, 400)

x, y = np.meshgrid(x, y)

def axes(ax):
    ax.axhline(0, alpha = 0.1)
    ax.axvline(0, alpha = 0.1)

fig, ax = plt.subplots(2, 2)

fig = plt.gcf()
fig.suptitle("Conics vizualization of a circle, ellipse, parabola and hyperbola.")

a = 0.3
axes(ax[0,0])
ax[0,0].contour(x, y, (y**2 - 4*a*x), [2], colors='k')
ax[0,0].set_ylabel('parabola')
ax[0,0].set_xlabel('(y**2 - 4*a*x), a=0.3')

a = 2
b = 2
axes(ax[0,1])
ax[0,1].contour(x, y,(x**2/a**2 + y**2/b**2), [1], colors='k')
ax[0,1].set_title('circle')
ax[0,1].set_xlabel('(x**2/a**2 + y**2/b**2), a=2, b=2')
ax[0,1].legend()

a = 4
b = 2
axes(ax[1,0])
ax[1,0].contour(x, y,(x**2/a**2 + y**2/b**2), [1], colors='k')
ax[1,0].set_ylabel('Ellips')
ax[1,0].set_xlabel('(x**2/a**2 + y**2/b**2), a=4, b=2')

a = 2
b = 1
axes(ax[1,1])
ax[1,1].contour(x, y,(x**2/a**2 - y**2/b**2), [1], colors='k')
ax[1,1].set_ylabel('hyperbola')
ax[1,1].set_xlabel('(x**2/a**2 - y**2/b**2), a=2, b=1')

plt.show()

I tired

label='(y**2 - 4*a*x), a=0.3'

and

plt.legend(loc='best')

both dosent work


Solution

  • The issue is that contour plots do not really support labels (they work a bit different than the usual plot). If you need to use contour, I don't see a better way (please, proof me wrong!) then "sneaking" the label in by adding a regular plot with just a single point. E.g. like this:

    a = 2
    b = 1
    axes(ax[1, 1])
    ax[1, 1].contour(x, y, (x ** 2 / a ** 2 - y ** 2 / b ** 2), [1], colors='k')
    ax[1, 1].set_ylabel('hyperbola')
    # Here we add the 'plot' at (0, 0)
    ax[1, 1].plot(0, 0, color='k', label='(x**2/a**2 - y**2/b**2), a=2, b=1')
    # Call the legend function of the axis.
    ax[1, 1].legend()
    

    Doing so on all axis yields

    Plot result