Pyplot: Control texts clip in one direction

Viewed 47

I am trying to change the plot window extents on an annotated plot to "zoom" into a certain window of interest. My text annotations fall outside of the plot window. If I use clip_on = True then all the text is hidden, but I just want to trim the text outside of the x-axis.

import matplotlib.pyplot as plt
x = [0,2,4,6,8,10]
y = [3,2,5,9,6,7]

plt.plot(x,y)
for i in range(len(x)):
    plt.text(x[i],11, '%d' %y[i])    
plt.axis([0,5,0,10])

Full data:

enter image description here

Reduced window:

enter image description here

Desired output:

enter image description here

1 Answers

This isn't fancy at all, but it works for x_max 1 to 10:

import matplotlib.pyplot as plt

x = [0,2,4,6,8,10]
y = [3,2,5,9,6,7]

x_max = 5 

plot_axis = [0,x_max,0,10]

if plot_axis[1] == x[-1:][0]:
    range_set = range(len(x))
else:
    try:
        x_idx = x.index(plot_axis[1])
    except: 
        x_idx = x.index(plot_axis[1]-1)  
        
    range_set = range(x_idx+1)
        
plt.plot(x,y)
for i in range_set:
    plt.text(x[i],11, '%d' %y[i])    
plt.axis(plot_axis)
plt.show()

Note: There isn't a sanity check for x_max = 0 or >10 implemented, but from your plt.axis([0,5,0,10]) it seems you had this in manually in check anyway.

Related