首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在matplotlib图中显示原点轴(x,y)

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

Stack Overflow用户
提问于 2014-09-05 23:26:37
回答 2查看 118.1K关注 0票数 62

我有以下简单的图,我想显示原点轴(x,y)。我已经有了网格,但我需要强调x,y轴。

这是我的代码:

x = linspace(0.2,10,100)
plot(x, 1/x)
plot(x, log(x))
axis('equal')
grid()

我已经看到了this的问题。公认的答案是建议使用"Axis spine“,并且只需链接到一些示例。然而,这个例子太复杂了,使用了子图。在我的简单示例中,我不知道如何使用"Axis spine“。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-09-05 23:31:42

使用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')

我得到了:

(您看不到垂直轴,因为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()

可选择使用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

使用脊椎的set_position方法

以下是set_position method of spines的文档

脊椎位置由(位置类型,数量)的2元组指定。职位类型包括:

  • ‘out’:将脊椎从数据区域向外放置指定数量的点。(负值指定将

spine inward.)

  • 'axes‘:将脊椎放置在指定的轴坐标处(from 0.0-1.0).

  • 'data’:将脊椎放置在指定的数据坐标。

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

数据中心('axes',0.5)

  • 'zero‘-> (’

  • ‘,0.0) ->

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

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

其中,system是“向外”、“轴”或“数据”,并且position位于该坐标系中的位置。

票数 102
EN

Stack Overflow用户

发布于 2021-01-18 23:20:59

对于那些想要像我一样搜索它的人,让我来回答这个(相当古老的)问题。尽管它建议所有工作解决方案,但我认为(唯一)提供的答案way太复杂了,当涉及到问题中描述的如此简单的情况时(注意:此方法需要您指定所有轴端点)。

我在matplotlib's pyplot上的one of the first tutorials中找到了一个简单有效的解决方案。在创建plot之后,添加以下行就足够了

plt.axis([xmin, xmax, ymin, ymax])

如下例所示:

from matplotlib import pyplot as plt

xs = [1,2,3,4,5]
ys = [3,5,1,2,4]

plt.scatter(xs, ys)
plt.axis([0,6,0,6])  #this line does the job
plt.show()

这将产生以下结果:

matplotlib plot with axes endpoints specified

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25689238

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档