在matplotlib图中显示原点轴(x,y)

Mar*_*ter 34 matplotlib ipython ipython-notebook

我有跟随简单的情节,我想显示原点轴(x,y).我已经有网格,但我需要强调x,y轴.

在此输入图像描述

这是我的代码:

x = linspace(0.2,10,100)
plot(x, 1/x)
plot(x, log(x))
axis('equal')
grid()
Run Code Online (Sandbox Code Playgroud)

我见过这个问题.接受的答案建议使用"轴脊柱",只是链接到一些例子.然而,使用子图表的例子太复杂了.我无法弄清楚,如何在我的简单示例中使用"Axis spine".

Pau*_*l H 59

使用subplots不是太复杂,刺可能是.

愚蠢,简单的方式:

%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')
Run Code Online (Sandbox Code Playgroud)

我得到:

用轴线

(由于下限x限制为零,因此无法看到垂直轴.)

替代使用简单的刺

%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()
Run Code Online (Sandbox Code Playgroud)

with_spines

替代使用seaborn(我最喜欢的)

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
Run Code Online (Sandbox Code Playgroud)

with_seaborn

使用set_position脊柱的方法

以下是set_position方法的文档:

脊柱位置由2个元组(位置类型,数量)指定.职位类型是:

  • '向外':将脊椎从数据区域中移出指定的点数.(负值指定
    向内放置脊柱.)

  • 'axes':将脊柱放在指定的Axes坐标处(从0.0到1.0).

  • 'data':将脊柱放在指定的数据坐标上.

此外,简写符号定义了一个特殊的位置:

  • 'center' - >('axes',0.5)
  • '零' - >('数据',0.0)

所以你可以把左脊椎放在任何地方:

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

其中system是"向外","轴"或"数据"以及position该坐标系中的位置.


Ken*_*ans 7

自从提出这个问题以来已经过去了一段时间了。对于 Matplotlib 3.6.2,它看起来像这样:

plt.axhline(0, color='black', linewidth=.5)
plt.axvline(0, color='black', linewidth=.5)
Run Code Online (Sandbox Code Playgroud)

还有其他选择。