dmasny99
dmasny99

Reputation: 21

How to properly set labels in contourf subplots?

I am trying to get rid of these purple points on the picture below. Here is my code:

p_values = [0., 0.05, 0.25, 0.5, 1, 1.5, 2, 5, 10, np.inf]
xx, yy = np.meshgrid(np.linspace(-3, 3, num = 101),
                     np.linspace(-3, 3, num = 101))

fig, axes = plt.subplots(ncols = (len(p_values) + 1) // 2,
                         nrows = 2, figsize = (16, 7))

for p, ax in zip(p_values, axes.flat):
    ### BEGIN Solution (do not delete this comment)
    z = np.linalg.norm([xx, yy], ord = p, axis = 0) 
    ax.contourf(yy, xx, z, 25, cmap = 'coolwarm')
    ax.contour(yy, xx, z, [1], colors = 'fuchsia', linewidths = 3)
    ax.set_title(f'p = {p}')
    ax.legend([f'$x: |x|_{{{p}}} = 1$']);
    ### END Solution (do not delete this comment)
plt.show()

Which parameters should be specified in ax.legend() in order to plot the graph clear.

Upvotes: 2

Views: 753

Answers (1)

JohanC
JohanC

Reputation: 80299

You could create the legend using an explicit handle. In this case the fuchsia colored line is stored as the last element of ax.collections. Creating the legend with only labels, when there were no "handles with labels" set, could be the cause of the weird purple dots.

import matplotlib.pyplot as plt
import numpy as np

p_values = [0., 0.05, 0.25, 0.5, 1, 1.5, 2, 5, 10, np.inf]
xx, yy = np.meshgrid(np.linspace(-3, 3, num=101),
                     np.linspace(-3, 3, num=101))

fig, axes = plt.subplots(ncols=(len(p_values) + 1) // 2,
                         nrows=2, figsize=(16, 7))
cmap = plt.get_cmap('magma').copy()
cmap.set_extremes(over='green', under='black', bad='turquoise')
for p, ax in zip(p_values, axes.flat):
    ### BEGIN Solution (do not delete this comment)
    z = np.linalg.norm([xx, yy], ord=p, axis=0)
    cnt = ax.contourf(yy, xx, z, 25, cmap='coolwarm')
    ax.contour(yy, xx, z, [1], colors='fuchsia', linewidths=3)
    ax.set_title(f'p = {p}')
    ax.legend(handles=[ax.collections[-1]], labels=[f'$x: |x|_{{{p}}} = 1$'])
    plt.colorbar(cnt, ax=ax)
    ### END Solution (do not delete this comment)
plt.tight_layout()
plt.show()

showing contour line in legend

Upvotes: 2

Related Questions