如何从 matplotlib 图中删除微秒?

How to remove microseconds from matplotlib plot?

我已经完成了 pylab 示例和许多轴格式问题,但我仍然无法从下图中的 x 轴上删除微秒。

尝试更改 axis/tick 属性及其输出之前的原始代码。

#filenames to be read in
file0 = 'results'         


#Get data from file strore in record array
def readIn(fileName):
    temp = DataClass()
    with open('%s.csv' % fileName) as csvfile:
        temp = mlab.csv2rec(csvfile,names = ['date', 'band','lat'])
    return temp

#plotting function(position number, x-axis data, y-axis data,
#                       filename,data type, units, y axis scale)
def iPlot(num,xaxi,yaxi,filename,types, units,scale):
    plt.subplot(2,1,num)
    plt.plot_date(xaxi,yaxi,'-')
    plt.title(filename + "--%s" % types )
    plt.ylabel(" %s  %s " % (types,units))
    plt.ylim(0,scale)
    plt.xticks(rotation=20)



# Set plot Parameters and call plot funciton
def plot():
    nameB = "Bandwidth"
    nameL = "Latency"
    unitsB = " (Mbps)"
    unitsL = "(ms)"
    scaleB = 30
    scaleL = 500

    iPlot(1,out0['date'],out0['lat'],file0,nameL,unitsL,scaleL)
    iPlot(2,out0['date'],out0['band'],file0,nameB,unitsB,scaleB)

def main():
    global out0 
    print "Creating plots..."

    out0 = readIn(file0)
    plot()

    plt.show()

main()

我的尝试是通过添加以下内容来更改上面的代码:

months   = date.MonthLocator()  # every month
days     = date.DayLocator()
hours    = date.HourLocator()
minutes    = date.MinuteLocator()
seconds   = date.SecondLocator()


def iPlot(num,xaxi,yaxi,filename,types, units,scale):
    plt.subplot(2,1,num)
    plt.plot_date(xaxi,yaxi,'-')
    plt.title(filename + "--%s" % types )
    plt.ylabel(" %s  %s " % (types,units))
    plt.ylim(0,scale)

    # Set Locators
    ax.xaxis.set_major_locator(days)
    ax.xaxis.set_minor_locator(hours)

    majorFormatter = date.DateFormatter('%M-%D %H:%M:%S')
    ax.xaxis.set_major_formatter(majorFormatter)
    ax.autoscale_view()

我设置的主要格式化程序是否被默认覆盖?有没有办法只关闭微秒而不影响其他格式?我不太清楚微秒的来源,因为我的数据包含 none。

你的代码有几个问题。首先,它不起作用(我的意思是即使我制作了所有模拟样本数据它也不起作用)。其次,这并不是一个真正展示错误的最小工作示例,我无法弄清楚你的 date 是什么,我想 matplotlib.dates?第三,我看不到你的情节(你的完整标签也有 '%M-%D 部分)

现在我遇到的问题是,我无法弄清楚你是如何通过 ('%M-%D %H:%M:%S') 这行的,这让我的语法不正确。 (python2.6.6 和 3.4 上的 Matplotlib 1.3.1 Win7)。我看不到你的 ax 是什么,或者你的数据是什么样子的,当涉及到这样的事情时,所有这些都会有问题。即使时间跨度过大也会导致滴答声 "overflow"(尤其是当您尝试将小时定位器放在年份范围内时,即我认为会在 7200 滴答声处抛出错误?)

同时,这是我的最小工作示例,它显示的行为与您的不同。

import matplotlib as mpl
import matplotlib.pyplot as plt
import datetime as dt

days     = mpl.dates.DayLocator()
hours    = mpl.dates.HourLocator()


x = []
for i in range(1, 30):
    x.append(dt.datetime(year=2000, month=1, day=i,
                             hour=int(i/3), minute=i, second=i))
y = []
for i in range(len(x)):
    y.append(i)

fig, ax = plt.subplots()
plt.xticks(rotation=45)
ax.plot_date(x, y, "-")

ax.xaxis.set_major_locator(days)
ax.xaxis.set_minor_locator(hours)

majorFormatter = mpl.dates.DateFormatter('%m-%d %H:%M:%S')
ax.xaxis.set_major_formatter(majorFormatter)
ax.autoscale_view()

plt.show()

(这一切可能不应该是一个答案,也许它会对你有所帮助,但它太长了,无法作为评论)。

如果您不使用子图,请不要使用它们。

只需删除对 subplot()subplots() 函数的任何提及,然后要获得轴句柄,您可以使用:ax = plt.gca() 在对 ax 的任何引用之上。

可能是这样的:

...
# Set Locators
ax = plt.gca()
ax.xaxis.set_major_locator(days)
ax.xaxis.set_minor_locator(hours)
...

然后,您将收到 ValueError: Invalid format string 错误 - 可能是因为您 %D 不是 valid strftime string formatting directive。 (你可能想要 %m-%d %H:%M:%S。)如果你解决了这个问题,你的绘图将与你的格式化程序一起显示。