2

I'm working on a script that plots a pps count versus time from a csv file. Everything works up to this point however I can't seem to figure out how to change the interval at which the ticks/tick-labels occur at on the X-axis, I want there to be 60 timestamps/tick instead of the default. Here's where I'm at:

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

I've tried plt.xticks(range(60)) but when the plot generates, it has nothing on it.

4

2 回答 2

3

bmu's answer above works. But it might be helpful to others to see a more general way of rescaling the xticks and xlabels in a plot. I have generated some example data instead of using a csv file.

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')                                     
于 2012-05-22T14:52:11.957 回答
2

Have a look at the date demo.

You can use the HourLocator or the MinuteLocator together with an adapted 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)
于 2012-05-19T00:13:59.480 回答