改变 matplotlib 坐标轴设置

9
我该如何控制pyplot绘图的轴设置?我只是简单地执行了以下操作:
    pylab.plot(*self.plot_generator(low, high))

    pylab.show()

我得到了我想要的结果,如下所示:

alt text

但是我希望x轴从0开始而不是从底部开始。我该怎么做?

2个回答

19
# create some data
x = np.linspace(-np.pi,np.pi,100)
y = np.cos(2.5*x)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y, mfc='orange', mec='orange', marker='.')

# using 'spines', new in Matplotlib 1.0
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

ax.axhline(linewidth=2, color='blue')
ax.axvline(linewidth=2, color='blue')
show()

alt text


这看起来就是我需要的,还有@Joe Kington的评论。 - Falmarri
您可以在此处找到有关如何使用脊柱的更一般描述:http://matplotlib.org/examples/pylab_examples/spine_placement_demo.html - Marcos Alex
2
你能解释一下为什么这里要使用 ax.spines 吗?据我所知,所有的方法 set_positionset_color 都是 matplotlib.spines.Spine 类对象的成员。这很令人困惑。 - haccks
没错。ax.spines 是一个包含四个 Spine 对象的 OrderedDict'left''right''top''bottom' - teekarna
这里不需要使用 axhlineaxvline 命令。如果想要改变坐标轴的线宽或颜色,最好是改变坐标轴属性。 - teekarna

12

将x轴的起始点设置为0:

pylab.xlim(xmin=0)
将 y 轴起始值设为 0:
pylab.ylim(ymin=0)

pylab.plot调用之后,加入以下任意一行代码(或两行都加入,如果需要的话)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接