Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

merge two scatter markers into one for the legend in matplot

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# 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!

>Solution :

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.

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")
ax.legend(loc="best")

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading