2

I have been through the pylab examples and many axis formatting questions, but am still unable to remove the microseconds from the x-axis in the plot below.

Original code before trying to alter axis/tick properties and its output.

enter image description here

#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()

My attempt was to alter the code above by adding:

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()

Is the major formatter I'm setting being over written by a default on? Is there a way to just turn off the microseconds without mucking with the rest of the format? I am fairly unclear on where the microseconds come from as my data contains none.

5
  • Where is ax being set? from subplots(...)? Can you show that line? Commented Mar 4, 2015 at 23:26
  • fig,ax = plt.subplots() Happens at very top of code Commented Mar 4, 2015 at 23:29
  • Are your Seconds floats? Could you round them down to ints for plotting? Commented Mar 4, 2015 at 23:30
  • Are you passing no arguments to subplots? Is it simply fig, ax = subplots()? Commented Mar 4, 2015 at 23:30
  • jedwards --yes, cphlewis-- they are datetime Commented Mar 4, 2015 at 23:32

2 Answers 2

3

I've a couple of problems with your code. First, it doesn't work (and I mean it doesn't work even when I make all the mock sample data). Second, it's not really a minimal working example showcasing what's wrong, I can't figure out what your date is, I presume matplotlib.dates? Third I can't see your plot (your full label with the '%M-%D part on it as well)

Now issues I have with that is, I can't figure out how do you even get past the line with ('%M-%D %H:%M:%S') which throws an incorrect syntax my way. (Matplotlib 1.3.1 Win7 both on python2.6.6 and 3.4). I can't see what your ax is, or how does your data look like, all of this can be problematic when it comes to stuff like this. Even having an overly large time span can cause ticks to "overflow" (especially when you try to put hour locators on a range of years, i.e. that throws an error at 7200 ticks I think?)

Meanwhile, here's my min working example that doesn't display the same behavior as yours.

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()

enter image description here

(This all shouldn't probably be an answer, maybe it'll turn out it helps you, but it's too long to be a comment).

Sign up to request clarification or add additional context in comments.

4 Comments

You are correct on a bunch of what you said. After reading some of the answers/comments parts of my understanding of the plotting are fundamentally flawed... I am going to post the full original code and plot output to clarify how my code works.
@Tom try to isolate your problem to a separate smaller script the best you can, not post the full code. If it's long, that helps even less. Apart from that, good luck!
I think I'm just missing the proper way to set ax with the way im doing the subplots
@Tom I don't see you creating an fig or ax instance anywhere up there. Notice how I did fig, ax = plt.subplots() so you should also do f, axarr = plt.subplot(2, 1, m) or even possibly a fig, ax = plt.subplots(2). In the code you added you refer to ax instance which doesn't exist and that should result in an error. In your original example you're working with the plt command, which implicitly creates and then selects an fig and an ax. See this code where it says # Two subplots, the axes array is 1-d.
0

If you're not using subplots, don't use them.

Simply remove any mention of the subplot() or subplots() functions, then to get an axis handle you could use: ax = plt.gca() above any reference to ax.

Maybe something like:

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

Then, you'll get a ValueError: Invalid format string error -- likely because you have %D isn't a valid strftime string formatting directive. (You probably want %m-%d %H:%M:%S.) If you fix that, your plot will display with your formatter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.