0

Assume I have a function, that represents a path of a driving car:

import numpy as np
import matplotlib.pyplot as plt

# positions of the car
x = np.linspace(0, 20, 100)
y = np.sin(x)

fig, ax = plt.subplots(figsize=(12, 8))
ax.plot(x, y)

enter image description here

The car stops at certain positions and I want to mark these position in the graph by using the pause symbol, which some of you are certainly familiar with. The symbol is simply two vertical lines. Unfortunately, matplot does not have a marker that looks like that, however, matplot comes with the vertical line as a marker. So, as a plan B i came up with the following implementation:

# position where the car stops
x_stop = np.array([1, 5, 10])
y_stop = np.sin(x_stop)

# to create a stop symbol we shift the vertical line from matplot
shift = 0.1
ax.scatter(x_stop - shift, y_stop, marker='|', color='r', s=225, label='stop')
ax.scatter(x_stop + shift, y_stop, marker='|', color='r', s=225, label='stop')

plt.legend(loc='best')

enter image description here

The issue with this is that the legend obviously does not make sense. What I would like to have is the two markers next to each other in the legend, just like they appear in the graph on the path of the car. Is there a way to achieve this? Any other approach or a fix for my problem is fine!

kklaw
  • 452
  • 2
  • 4
  • 14

1 Answers1

1

Following this answer, you can use LaTeX to create a custom symbol for matplotlib markers. In this case, it's simple: marker = "$||$". The dollar signs wrap the LaTeX. As pointed out by @kklaw, the scatter plot's zorder is lower than the line, so the zorder needs to be adjusted to bring them in front.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 20, 100)
y = np.sin(x)

fig, ax = plt.subplots(figsize=(12, 8))
ax.plot(x, y)

x_stop = np.array([1, 5, 10])
y_stop = np.sin(x_stop)

shift = 0.1
ax.scatter(x_stop, y_stop, marker="$||$", color="r", s=225, label="stop", zorder=2)
ax.legend(loc="best")

jared
  • 4,165
  • 1
  • 8
  • 31
  • 1
    Oh, that is very interesting. The markers can also be made more visible by adjusting the zorder, if anyone is wondering. – kklaw Jul 24 '23 at 19:44
  • @kklaw Right, you can adjust the zorder to bring them in front. I didn't realize they were behind. I'll update my solution to mention that. – jared Jul 24 '23 at 21:23