Python - Matplotlib - 设置X轴范围 - 每秒绘制数据包数

时间:2012-05-18 23:50:50

标签: python matplotlib

我正在编写一个脚本,用于从csv文件中绘制pps计数与时间的关系。一切都达到了这一点,但我似乎无法弄清楚如何更改刻度线/刻度标签出现在X轴上的间隔,我希望有60个时间戳/刻度而不是默认值。这就是我所在的地方:

import matplotlib
matplotlib.use('Agg')                   
from matplotlib.mlab import csv2rec     
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from pylab import *

data = csv2rec('tpm_counter.log', names=['packets', 'time']) # reads in the data from the csv as column 1 = tweets column 2 = time
rcParams['figure.figsize'] = 12, 4                           # this sets the ddimensions of the graph to be made
rcParams['font.size'] = 8

fig = plt.figure()
plt.plot(data['time'], data['packets'])                      # this sets the fields to be graphed
plt.xlabel("Time(minutes)")                                  # this sets the x label
plt.ylabel("Packets")                                        # this sets the y label
plt.title("Packets Capture Log: Packets Per Minute")         # this sets the title

#plt.xticks(range(60)) --- nothing shows on the graph if I use this

fig.autofmt_xdate(bottom=0.2, rotation=90, ha='left')

plt.savefig('tpm.png')                                      # this sets the output file name

我已经尝试了plt.xticks(range(60))但是当情节生成时,它上面没有任何内容。

2 个答案:

答案 0 :(得分:3)

bmu的回答是有效的。但是,对于其他人来说,在一个情节中看到一种更通用的重新缩放xticks和xlabels的方法可能会有所帮助。我生成了一些示例数据,而不是使用csv文件。

import matplotlib            
import matplotlib.pyplot as plt
from pylab import *

time=range(5000) #just as an example
data=range(5000) # just as an example

fig = plt.figure()
plt.plot(time,data)                      # this sets the fields to be graphed
plt.xlabel("Every 60th point")           # this sets the x label
plt.ylabel("Data")                       # this sets the y label
plt.title("Rescaling axes")              # this sets the title

#Slice the data into every 60th point. We want ticks at these points
tickpos=data[::60] 
#Now create a list of labels for each point...
ticklabels=[]
for point in tickpos:
    ticklabels.append(str(point/60))  

plt.xticks(tickpos,ticklabels) # set the xtick positions and labels

plt.savefig('tpm.png')                                     

答案 1 :(得分:2)

查看date demo

您可以将HourLocator或MinuteLocator与改编后的DateFormatter一起使用。

import matplotlib.dates as mdates
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot_date(data['time'], data['packets']) 
hours = mdates.HourLocator() 
fmt = mdates.DateFormatter('%H:%M')
ax.xaxis.set_major_locator(hours)
ax.xaxis.set_major_formatter(fmt)