Home > Software engineering >  How to get the line's label if multiple graphs have been plotted?
How to get the line's label if multiple graphs have been plotted?

Time:08-29

plt.plot(x, y, label = name1)
plt.plot(x, y, label = name2)
plt.plot(x, y, label = name3)
plt.show()

How to get the label when I click the line or better if I can get this information directly in the graph window like I get the x and y axis values on bottom right.

CodePudding user response:

The fastest way would be to add a enter image description here

I am not sure if this is what you are looking for? But you can easily name your graphs by using the Legend. the first graph will be the first in your Legendlist. The important code is between the slash :-)

import matplotlib.pyplot as plt
import numpy as np


# Select length of axes and the space between tick labels
xmin, xmax, ymin, ymax = -10, 10, -10, 10
ticks_frequency = 1

# Plot points
fig, ax = plt.subplots(figsize=(10, 10))

#//////////////////////////////////////////////////////////////////////////////

# x range
x = np.arange(-5, 5., 0.025)

# f1
y1 = 3*x 4
f1 = ax.plot(x, y1, lw = 3, alpha = 0.5, color="blue")

# f2
y2 = 1*x 1
f2 = ax.plot(x, y2, lw = 3, alpha = 0.5, color="orange")

# f3
y3 = -2*x 8
f3 = ax.plot(x, y3, lw = 3, alpha = 0.5, color="red")

# legend
ax.legend(["Gerade 1", "Gerade 2", "Gerade 3"])

#//////////////////////////////////////////////////////////////////////////////

# Set identical scales for both axes
ax.set(xlim=(xmin-1, xmax 1), ylim=(ymin-1, ymax 1), aspect='equal')

# Set bottom and left spines as x and y axes of coordinate system
ax.spines['bottom'].set_position('zero')
ax.spines['left'].set_position('zero')

# Remove top and right spines
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

# Create 'x' and 'y' labels placed at the end of the axes
ax.set_xlabel('x', size=14, labelpad=-24, x=1.03)
ax.set_ylabel('y', size=14, labelpad=-21, y=1.02, rotation=0)

# Create custom major ticks to determine position of tick labels
x_ticks = np.arange(xmin, xmax 1, ticks_frequency)
y_ticks = np.arange(ymin, ymax 1, ticks_frequency)
ax.set_xticks(x_ticks[x_ticks != 0])
ax.set_yticks(y_ticks[y_ticks != 0])

# Create minor ticks placed at each integer to enable drawing of minor grid
# lines: note that this has no effect in this example with ticks_frequency=1
ax.set_xticks(np.arange(xmin, xmax 1), minor=True)
ax.set_yticks(np.arange(ymin, ymax 1), minor=True)

# Draw major and minor grid lines
ax.grid(which='both', color='grey', linewidth=1, linestyle='-', alpha=0.2)

# Draw arrows
arrow_fmt = dict(markersize=4, color='black', clip_on=False)
ax.plot((1), (0), marker='>', transform=ax.get_yaxis_transform(), **arrow_fmt)
ax.plot((0), (1), marker='^', transform=ax.get_xaxis_transform(), **arrow_fmt)

plt.show()
  • Related