how to add label to two superimposed matplotlib pots in python

To add labels to two superimposed matplotlib plots in Python, you can use the text function in matplotlib.pyplot. Here's an example:

main.py
import matplotlib.pyplot as plt
import numpy as np

# Generate some data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# Create a figure and axes
fig, ax = plt.subplots()

# Plot the first line
ax.plot(x, y1, label='Sin')

# Plot the second line
ax.plot(x, y2, label='Cos')

# Add the legend
ax.legend()

# Add labels to the plots
ax.text(2, 0.8, 'Sin', fontsize=12, color='blue')
ax.text(4, -0.8, 'Cos', fontsize=12, color='orange')

# Show the plot
plt.show()
475 chars
27 lines

In this example, we first generate some data using numpy. Then, we create a figure and axes using plt.subplots(). We plot the two lines using ax.plot() and add labels to each line using ax.text(). Finally, we add a legend using ax.legend() and display the plot using plt.show().

The ax.text() function takes the x and y coordinates of the label as the first two arguments. You can adjust the position of the labels by changing these coordinates. The fontsize and color arguments can be used to customize the appearance of the labels.

Note that the label parameter in ax.plot() is used to provide the legend label, while the ax.text() is used to add labels directly on the plot.

I hope this helps!

related categories

gistlibby LogSnag