I'm trying to put labels for each line in matplotlib.hlines:
from matplotlib import pyplot as plt
plt.hlines(y=1, xmin=1, xmax=4, label='somelabel1')
plt.hlines(y=2, xmin=2, xmax=5, label='somelabel2')
I need a plot with two horizintal lines with labels on 'y' axis for each line. Instead of it I get a plot without labels, with only coordinates (see the sample image). Is it possible to put lables for each line into the plot?
Axis Titles You can customize the title of your matplotlib chart with the xlabel() and ylabel() functions. You need to pass a string for the label text to the function.
The label
kwarg
is to specify the string that's displayed in a legend
, not necessarily on the line itself. If you want the label to appear in your plot, you'll want to use a text
object instead
plt.hlines(y=1, xmin=1, xmax=4)
plt.text(4, 1, ' somelabel1', ha='left', va='center')
plt.hlines(y=2, xmin=2, xmax=5)
plt.text(2, 2, 'somelabel2 ', ha='right', va='center')
If you instead want special y axis labels for these, you can use a custom formatter.
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
plt.hlines(y=1, xmin=1, xmax=4)
plt.hlines(y=2, xmin=2, xmax=5)
def formatter(y, pos):
if y == 1:
return 'label1'
elif y == 2:
return 'label2'
else:
return y
plt.gca().yaxis.set_major_formatter(ticker.FuncFormatter(formatter))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With