python axhline label not showing up in plot
Asked Answered
F

3

10

I have the following little function:

def plotresults(freqs,power,prob,title,sigP):
    pl.suptitle(title)
    ax1 = pl.subplot(2,1,1)
    ax1.axhline(y=sigP, color='r', ls='--',label='p=0.05')
    pl.plot(freqs,power)
    ax1.set_ylabel('Spectral Power')

    ax2 = pl.subplot(2,1,2)
    ax2.axhline(y=0.05, color='r', ls='--', label='p=0.05')
    pl.semilogy(freqs,prob)
    ax2.set_xlabel(r'Frequency (years$^{-1}$)')
    ax2.set_ylabel('p-value')
    pl.savefig('lsfast/figs/'+title+'.png')
    pl.close()

It plots fine and draws the lines where they should be, but the line labels don't appear anywhere. What am I doing wrong? AN example of the output is attached:

Example plot created using the above function

Finish answered 11/8, 2015 at 19:35 Comment(0)
V
17

The label kwarg for plot sets the label that's used by legend. To display it you can add a legend to your plot. Alternately, you might want to use annotate instead.

Viscid answered 11/8, 2015 at 20:2 Comment(2)
Could you please add a couple of lines of code to show how to display a legend using the label defined in axhline?Presbyopia
Calling plt.legend() displayed the label for me, however I believe you can also call that on ax. Ex: import matplotlib.pyplot as plt; plt.figure(); plt.axhline(y=0.5, color='r', linestyle='--', label='label'); plt.legend(); plt.show()Erv
G
5

I don't think attaching a label to a line is meant to draw this label to the plot, it just associates this label with the line and can be used to create a legend.

Gefell answered 11/8, 2015 at 20:0 Comment(0)
A
0

I find using text is pretty straightforward:

y = 42
ax.text(ax.get_xlim()[1] + 0.1, y, f'y={y}')

ax.get_xlim()[1] gets the position of our right position of the plot' right coordinate, use [0] for left.

enter image description here Here's your full example:

import matplotlib.pyplot as plt
import numpy as np  

# Sample random data 
freqs = np.linspace(0.1, 10, 100)  
power = np.random.rand(100)  
prob = np.random.rand(100) 
sigP = 0.05  
title = "Ag2010"  

plt.figure(figsize=(8, 6))  
ax1 = plt.subplot(2, 1, 1)
ax2 = plt.subplot(2, 1, 2)

# Subplot 1
y1_val = 0.5

ax1.plot(freqs, power)
ax1.axhline(y=y1_val, color='r', ls='--', label='p=0.05')
ax1.text(ax1.get_xlim()[1] + 0.1, y1_val, f'y={y1_val}')

ax1.set_ylabel('Spectral Power')

# Subplot 2
y2_val = 0.1
ax2.semilogy(freqs, prob)
ax2.axhline(y=0.1, color='r', ls='--', label='p=0.05')
ax2.text(ax2.get_xlim()[1] + 0.1, y2_val, f'y={y2_val:.0e}')
ax2.set_xlabel(r'Frequency (years$^{-1}$)')
ax2.set_ylabel('P-value')


plt.suptitle(title)


plt.show()

Acree answered 13/7, 2024 at 11:36 Comment(2)
Fine for a one-off but requires manual changes if you change the lineFinish
It will automatically change as y changeAcree

© 2022 - 2025 — McMap. All rights reserved.