In matplotlib, I want to make a line using matplotlib.pyplot
which is alternating black and yellow dashes, and then I want to include that line on the legend. How do I do that?
I could do something like:
JavaScript
x
15
15
1
from matplotlib import pyplot as plt, gridspec
2
import numpy as np
3
4
grid = gridspec.GridSpec(1,1)
5
ax = plt.subplot(grid[0,0])
6
7
x = np.arange(1,11)
8
y = x * 2
9
10
ax.plot(x, y, '-', color = 'black', linewidth = 1, label = 'my line')
11
ax.plot(x, y, '--', color = 'yellow')
12
ax.legend()
13
14
plt.show()
15
but then the line on the legend would appear as a solid black line, rather than as black-and-yellow dashes.
I did look at matplotlib.path_effects
but I can’t work out whether it’s possible to achieve what I want; I can outline or shadow the line, but I’m not sure I can overlay a differently-coloured dashed line.
Advertisement
Answer
Try this.
JavaScript
1
19
19
1
from matplotlib import pyplot as plt, gridspec, lines
2
3
import numpy as np
4
5
grid = gridspec.GridSpec(1,1)
6
ax = plt.subplot(grid[0,0])
7
8
x = np.arange(1,11)
9
y = x * 2
10
11
ax.plot(x, y, '-', color = 'black', linewidth = 5)
12
ax.plot(x, y, '--', color = 'lawngreen', linewidth = 5)
13
14
dotted_line1 = lines.Line2D([], [], linewidth=5, linestyle="--", dashes=(10, 1), color='lawngreen')
15
dotted_line2 = lines.Line2D([], [], linewidth=5, linestyle="-", dashes=(5, 4), color='black')
16
17
plt.legend([(dotted_line1, dotted_line2)], ["My Line"])
18
plt.show()
19
i increased the line width so it is clearly visible. As yellow was not that clear in a white background; changed it to green. Sorry about that. You can change colors any time any way :)