Matplotlib vline label parameter not showing
Asked Answered
B

3

19

I want to label my vertical lines with matplotlib's .vline command, but for some reason the label parameter doesn't do anything/show anything on the final plot. Does anyone know how to get the label to show?

plt.vlines(x=pah, ymin=0, ymax=0.6, colors='0.75', linestyles='dashed', label='PAHs')

Everything works apart from the label.

Many thanks,

L

Break answered 26/11, 2014 at 16:59 Comment(0)
S
29

The label keyword is displayed in the legend. You need create the legend explicitly to see the label in the plot:

plt.vlines([1,2,3], 0, 1, label='test')
plt.legend()
Strangles answered 26/11, 2014 at 17:4 Comment(2)
Thanks for that, makes logical sense now... But after staring at the screen for hours on end, you descend into madness.Break
Likewise, I am descending into madness too. What is the best way of showing labels on top of the y axis (that is, on ymax = plot.get_ylim()[1]) instead of the legend? (potentially a different label for each position of vlines)? For more context, I have the following issue with the labels: github.com/chapmanb/bcbio-nextgen/pull/1204Mendenhall
H
4

For text near your line as in this example use:

vline_value = 3

fig, ax = plt.subplots(figsize=(10,10))
ax.axvline(x=vline_value, ymin=0, ymax=1) 
x_bounds = ax.get_xlim()
ax.annotate(s='vline_value', xy =(((vline_value-x_bounds[0])/(x_bounds[1]-x_bounds[0])),1.01), xycoords='axes fraction', verticalalignment='right', horizontalalignment='right bottom' , rotation = 270)
fig.savefig('example')

Also, this short script holds more options if you want: https://pythonhosted.org/lineid_plot/#

Helvetia answered 21/2, 2016 at 15:39 Comment(0)
H
1

This works

plt.plot(x,y)
plt.vlines(x=pah, ymin=0, ymax=0.6, colors='0.75', linestyles='dashed', label='PAHs')
plt.legend()

but I don't know if this is what you expect

Hermie answered 26/11, 2014 at 17:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.