Matplotlib vlines图中y轴最小值未被应用

13

我在Matplotlib中绘制vlines图,我的数据集中所有y值都为> = 0。 我想让我的y轴底部刻度读取0,但是实际上它显示的是-500

以下是代码:

#!/usr/bin/env python

import numpy as np
from matplotlib import pyplot as plt, dates as mdates
import datetime as dt, time

# Read the data and turn it into a numpy array
#store = map(lambda line: map(int, line.strip().split()), open(name + '.txt').readlines())
store = [
    [1293606162197, 0, 0],
    [1293605477994, 63, 0],
    [1293605478057, 0, 0],
    [1293605478072, 2735, 1249],
    [1293606162213, 0, 0],
    [1293606162229, 0, 0],
]

nstore = np.array(store)

# Get arrays of each columns in the store array
d = nstore[:,0]
y1 = nstore[:,1]
y2 = nstore[:,2]

# Get arrays of values to be passed to matplotlib
s = d / 1000
dts = map(dt.datetime.fromtimestamp, s)
fds = mdates.date2num(dts)

# new figure and subplot
fig = plt.figure()
ax = fig.add_subplot(111)

# Plot using vlines
ax.vlines(fds, [0], y1, 'red')

# set xaxis tick settings
ax.xaxis.set_major_locator(mdates.MinuteLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d %H:%M'))

for label in ax.xaxis.get_ticklabels():
    label.set_rotation('vertical')

fig.subplots_adjust(bottom=.25)

# Set the y axis bottom limit to 0
ax.set_ylim(bottom=0)   # <<- THIS DOES NOT SEEM TO BE WORKING

# Save the plot figure
fig.savefig('out.png')

这是我得到的图表: enter image description here

有人可以指出我的问题在哪里吗?如果您能指导我找到所需的详细信息文档,那就太好了。谢谢。

这个问题是 Creating graph with date and time in axis labels with matplotlib 的后续问题。

1个回答

24

你可以在绘制数据之后手动设置限制,像这样:

pyplot.ylim(ymin=0)

Matplotlib会自动调整绘图范围,使其看起来更加“最佳”。有时,这意味着超出数据的严格范围。因此,您必须在绘图后更新限制范围,因为每次绘图都会更新范围(如果我理解正确的话)。

现在,您的方法可以起作用,但是必须在设置范围后更新图表:

ax.set_ylim(bottom=0)
pylot.draw()

(这在最新版本的matplotlib中在Mac OS X上的IPython shell中有效。)


啊,谢谢EOL,这样就可以工作了。在面向对象的风格中是否有类似的方法,因为我将同时进行许多绘图。 - sharat87
1
哦,天啊!我搞定了,将 ax.set_ylim(bottom=0) 更改为 ax.set_ylim(ymin=0) 就像魔法一样奏效,无需调用 .draw()。谢谢。 - sharat87
没错,我的 matplotlib.__version__ 显示的是 0.99.3,网站上最新版本似乎是 1.0.1,该死的 Ubuntu 软件源! - sharat87
@Shrikant:有趣但奇怪的是:在我的Mac OS X上(通过IPython),ax.set_ylim(ymin=…)不会更新图形,而且仍然需要使用pyplot.draw(),就像bottom=…一样。因此,更好的做法可能是始终使用可移植的代码并包括draw()。 :) - Eric O. Lebigot
1
记录一下:ax.set_ylim(ymin=…) 是旧语法,已经被答案中的 bottom=… 废弃。 - Eric O. Lebigot
显示剩余3条评论

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