I would like to mark one particular contour of a function with alternating and non-overlapping red and green dashes. My first idea was to use the parametrized dash minilanguage, but that gives an error:
import numpy as np
import matplotlib.pyplot as plt
# prepare the data
delta = 0.025
x = np.arange(-1.0, 1.0, delta)
y = np.arange(-1.0, 1.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-(X ** 2) - Y ** 2)
Z2 = np.exp(-((X - 1) ** 2) - (Y - 1) ** 2)
Z = (Z1 - Z2) * 2
# the actual plotting
plt.contour(X, Y, Z, levels=[1.1], linestyles=(0, (5, 5)), colors="red", alpha=0.5)
plt.contour(X, Y, Z, levels=[1.1], linestyles=(5, (5, 5)), colors="green", alpha=0.5)
plt.show()
ValueError: Do not know how to convert [0] to dashes
Any hints?
CodePudding user response:
The []
brackets were missing:
import numpy as np
import matplotlib.pyplot as plt
# prepare the data
delta = 0.025
x = np.arange(-1.0, 1.0, delta)
y = np.arange(-1.0, 1.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-(X ** 2) - Y ** 2)
Z2 = np.exp(-((X - 1) ** 2) - (Y - 1) ** 2)
Z = (Z1 - Z2) * 2
# the actual plotting
plt.contour(X, Y, Z, levels=[1.1], linestyles=[(0, (5, 5))], colors="red")
plt.contour(X, Y, Z, levels=[1.1], linestyles=[(5, (5, 5))], colors="green")
plt.show()
Thanks to @JohanC for the reply!
CodePudding user response:
To expand on Trenton's comment, linestyles
in the context of the contour()
function is not the same as in regular plots, as noted in the documentation:
matplotlib contour():
linestyles : {None, 'solid', 'dashed', 'dashdot', 'dotted'}, optional
Only applies to
contour
Because contour
is intended to generate a whole group of lines which themselves convey additional information, there is reduced ability to define the appearance of those lines, and so you can only choose from those 5 options (or a list of those options, applying each element to successive contours).