Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set labels in matplotlib.hlines

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?

enter image description here

like image 396
Vlad Avatar asked Apr 11 '17 14:04

Vlad


People also ask

How do you change the axis labels in matplotlib?

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.


1 Answers

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')

enter image description here

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))

enter image description here

like image 168
Suever Avatar answered Sep 28 '22 13:09

Suever