Matplotlib/pyplot: How to enforce axis range?

PythonGraphMatplotlibAxes

Python Problem Overview


I would like to draw a standard 2D line graph with pylot, but force the axes' values to be between 0 and 600 on the x, and 10k and 20k on the y. Let me go with an example...

import pylab as p

p.title(save_file)
p.axis([0.0,600.0,1000000.0,2000000.0])

#define keys and items elsewhere..
p.plot(keys,items)
p.savefig(save_file, dpi=100)

However, the axes still adjust to the size of the data. I'm interpreting the effect of p.axis to be setting what the max and min could be, not enforcing them to be the max or min. The same happens when I try to use p.xlim() etc.

Any thoughts?

Thanks.

Python Solutions


Solution 1 - Python

Calling p.plot after setting the limits is why it is rescaling. You are correct in that turning autoscaling off will get the right answer, but so will calling xlim() or ylim() after your plot command.

I use this quite a lot to invert the x axis, I work in astronomy and we use a magnitude system which is backwards (ie. brighter stars have a smaller magnitude) so I usually swap the limits with

lims = xlim()
xlim([lims[1], lims[0]]) 

Solution 2 - Python

To answer my own question, the trick is to turn auto scaling off...

p.axis([0.0,600.0, 10000.0,20000.0])
ax = p.gca()
ax.set_autoscale_on(False)

Solution 3 - Python

I tried all of those above answers, and I then summarized a pipeline of how to draw the fixed-axes image. It applied both to show function and savefig function.

  1. before you plot:

     fig = pylab.figure()
     ax = fig.gca()
     ax.set_autoscale_on(False)
    

This is to request an ax which is subplot(1,1,1).

  1. During the plot:

    ax.plot('You plot argument') # Put inside your argument, like ax.plot(x,y,label='test')
    ax.axis('The list of range') # Put in side your range [xmin,xmax,ymin,ymax], like ax.axis([-5,5,-5,200])
    
  2. After the plot:

  3. To show the image :

       fig.show()
    
  4. To save the figure :

       fig.savefig('the name of your figure')
    

I find out that put axis at the front of the code won't work even though I have set autoscale_on to False.

I used this code to create a series of animation. And below is the example of combing multiple fixed axes images into an animation. img

Solution 4 - Python

Try putting the call to axis after all plotting commands.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStuartView Question on Stackoverflow
Solution 1 - PythonSimon WalkerView Answer on Stackoverflow
Solution 2 - PythonStuartView Answer on Stackoverflow
Solution 3 - Pythontk_y1275963View Answer on Stackoverflow
Solution 4 - PythonPhilippView Answer on Stackoverflow