Matplotlib/pyplot: How to enforce axis range?

前端 未结 4 1685
时光取名叫无心
时光取名叫无心 2020-12-14 05:40

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.

相关标签:
4条回答
  • 2020-12-14 06:07

    Try putting the call to axis after all plotting commands.

    0 讨论(0)
  • 2020-12-14 06:15

    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]]) 
    
    0 讨论(0)
  • 2020-12-14 06:15

    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)
    
    0 讨论(0)
  • 2020-12-14 06:17

    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:

      1. To show the image :

        fig.show()
        
      2. 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

    0 讨论(0)
提交回复
热议问题