Issue
I have following simple plot, and I would like to display the origin axis (x, y). I already have grid, but I need the x, y axis to be emphasized.
this is my code:
x = linspace(0.2,10,100)
plot(x, 1/x)
plot(x, log(x))
axis('equal')
grid()
I have seen this question. The accepted answer suggests to use "Axis spine" and just links to some example. The example is however too complicated, using subplots. I am unable to figure out, how to use "Axis spine" in my simple example.
Solution
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:
(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()
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
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.
Answered By - Paul H
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.