2

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.

JohanC
  • 71,591
  • 8
  • 33
  • 66
dmasny99
  • 21
  • 3
  • Unfortunately, it doesn't work. It just outputs this warning 'No handles with labels found to put in legend.' and doesn't show any legends. Btw, thank you for comment. – dmasny99 Feb 10 '22 at 19:01
  • Now it works perfect, thank you! Please, can you post this comment as an answer in order to resolve the question. – dmasny99 Feb 10 '22 at 19:21
  • No, everything is fine. – dmasny99 Feb 10 '22 at 19:26

1 Answers1

1

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

JohanC
  • 71,591
  • 8
  • 33
  • 66