Add line x = y (45 degrees) within matplotlib axis bounds

I have a graph with different x- and y-limits:

fig, ax = subplots(ncols=1)
ax.set_xlim([0, 10])
ax.set_ylim([5, 10])

      

I would like to add a line x=y

to this graph, but keep the line within the axis.

My first, naive attempt is just

ax.plot(ax.get_xlim(), ax.get_xlim())

      

First, naive attempt

The improved try works, but is incredibly ugly, by code:

ax.plot([max(ax.get_xlim()[0], ax.get_ylim()[0]), 
         min(ax.get_xlim()[1], ax.get_ylim()[1])],
        [max(ax.get_xlim()[0], ax.get_ylim()[0]), 
         min(ax.get_xlim()[1], ax.get_ylim()[1])])

      

enter image description here

Is there a better way? I am using IPython version 1.2.1

inside Spyder 2.2.5

in Matplotlib version 1.3.1

and mpl.get_backend()

returns:

'module://IPython.kernel.zmq.pylab.backend_inline'

      

+3


source to share


1 answer


x = np.linspace(*ax.get_xlim())
ax.plot(x, x)

      



+6


source







All Articles