我已经完成了 pylab 示例和许多轴格式化问题,但仍然无法从下图中的 x 轴中删除微秒。
尝试更改轴/刻度属性及其输出之前的原始代码。
#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()
我设置的主要格式化程序是否被默认覆盖?有没有办法只关闭微秒而不用破坏格式的其余部分?我相当不清楚微秒从何而来,因为我的数据不包含任何微秒。
最佳答案
我对您的代码有一些问题。首先,它不起作用(我的意思是即使我制作了所有模拟样本数据它也不起作用)。其次,这并不是一个真正展示问题所在的最小工作示例,我无法弄清楚您的日期是什么,我猜想是 matplotlib.dates?第三,我看不到你的图(你的完整标签上也有 '%M-%D
部分)
现在我遇到的问题是,我不知道你如何通过 ('%M-%D %H:%M:%S')
这会以我的方式抛出错误的语法。 (Matplotlib 1.3.1 Win7 均在 python2.6.6 和 3.4 上)。我看不到你的ax
是什么,或者你的数据是什么样的,当涉及到这样的东西时,所有这些都可能会出现问题。即使时间跨度过大,也可能会导致刻度“溢出”(特别是当您尝试将小时定位器放在年份范围内时,即我认为在 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()
(这一切可能不应该是一个答案,也许它会对你有所帮助,但它太长了,无法成为评论)。
关于python - 如何从 matplotlib 图中删除微秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28866530/