show origin axis (x,y) in matplotlib plot

Using subplots is not too complicated, the spines might be.

Dumb, simple way:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0.2,10,100)
fig, ax = plt.subplots()
ax.plot(x, 1/x)
ax.plot(x, np.log(x))
ax.set_aspect('equal')
ax.grid(True, which="both")

ax.axhline(y=0, color="k")
ax.axvline(x=0, color="k")

And I get:

with axlines

(you can’t see the vertical axis since the lower x-limit is zero.)

Alternative using simple spines

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0.2,10,100)
fig, ax = plt.subplots()
ax.plot(x, 1/x)
ax.plot(x, np.log(x))
ax.set_aspect('equal')
ax.grid(True, which="both")

# set the x-spine (see below for more info on `set_position`)
ax.spines['left'].set_position('zero')

# turn off the right spine/ticks
ax.spines['right'].set_color('none')
ax.yaxis.tick_left()

# set the y-spine
ax.spines['bottom'].set_position('zero')

# turn off the top spine/ticks
ax.spines['top'].set_color('none')
ax.xaxis.tick_bottom()

with_spines

Alternative using seaborn (my favorite)

import numpy as np
import matplotlib.pyplot as plt
import seaborn
seaborn.set(style="ticks")

x = np.linspace(0.2,10,100)
fig, ax = plt.subplots()
ax.plot(x, 1/x)
ax.plot(x, np.log(x))
ax.set_aspect('equal')
ax.grid(True, which="both")
seaborn.despine(ax=ax, offset=0) # the important part here

with_seaborn

Using the set_position method of a spine

Here are the docs for a the set_position method of spines:

Spine position is specified by a 2 tuple of (position type, amount).
The position types are:

  • ‘outward’ : place the spine out from the data area by the specified number of points. (Negative values specify placing the
    spine inward.)

  • ‘axes’ : place the spine at the specified Axes coordinate (from
    0.0-1.0).

  • ‘data’ : place the spine at the specified data coordinate.

Additionally, shorthand notations define a special positions:

  • ‘center’ -> (‘axes’,0.5)
  • ‘zero’ -> (‘data’, 0.0)

So you can place, say the left spine anywhere with:

ax.spines['left'].set_position((system, poisition))

where system is ‘outward’, ‘axes’, or ‘data’ and position in the place in that coordinate system.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)