Can you add a number to a plotted line in matplotlib?

Viewed 2086

I am using matplotlib.pyplot to plot different lines. I can add a legend with a label to tell which line is which by color. Unfortunately I am color blind. Is it possible to write a number embedded in each line instead? The numbers could look like this.

enter image description here

These could then identify each line.

2 Answers

There is a nice little package matplotlib-label-lines that accomplishes this (the code is here on github).

After installing this package, your code could look something like this:

import numpy as np
import matplotlib.pyplot as plt
import labellines

x = np.linspace(0, 5, 100)

fig, ax = plt.subplots(1, 1)
ax.plot(x, x**2, linewidth=2, label="line example")
labellines.labelLines(ax.get_lines())

plt.show()

Which would give you something like this.

You could also you different line style, instead of color, in your legend. enter image description here

My answer is based on this question.

You can use latex math symbols in matplotlib. Since $1$ counts as latex math symbol, you can use it as marker.

Example with 0,1,2:

x, y, = np.arange(10), np.arange(10)

for a in range(3):

    plt.plot(x, a*y, alpha=0.5, marker='${}$'.format(a), markersize=10, label=a)

plt.legend()
plt.show()

enter image description here

edit

Plotting number only once on the curve

x, y, = np.arange(10), np.arange(10)

colors = ['teal', 'darkslateblue', 'orange']

for a in range(3):

    plt.plot(x, a*y, c=colors[a])
    plt.plot(x[a+3], a*y[a+3], alpha=0.5, marker='${}$'.format(a), markersize=10, label=a, c=colors[a])

plt.legend()
plt.show()

enter image description here

Related