6

I'm just starting with matplotlib. For example, having the following code:

import pylab

x = [1, 2, 3, 4, 5, 6, 7]
y = [2, 3, 4, 5, 6, 7, 8]

pylab.plot(x, y)
pylab.axhline(0, color="black")
pylab.axvline(0, color="black")

pylab.show()

enter image description here

Shows from 0 to 8 (Y) and 0 to 7 (X). Is there anyway to specify the range of the values showed in the axes? For example, from -5 to 3 and from -5 to 3. It doesn't matter if the function line is out of that range.

cdonts
  • 9,304
  • 4
  • 46
  • 72
  • 1
    possible duplicate of [Python, Matplotlib, subplot: How to set the axis range?](http://stackoverflow.com/questions/2849286/python-matplotlib-subplot-how-to-set-the-axis-range) – Søren V. Poulsen Jul 05 '14 at 01:54
  • 1
    Disagree about the duplicate, that question knew they should use `xlim`, but were getting messed up by order. – tacaswell Jul 05 '14 at 13:50

1 Answers1

7

You can use pylab.{x|y}lim(min, max):

import pylab

x = [1, 2, 3, 4, 5, 6, 7]
y = [2, 3, 4, 5, 6, 7, 8]

pylab.plot(x, y)
pylab.axhline(0, color="black")
pylab.axvline(0, color="black")

# Here we go:
pylab.xlim(-5, 3)
pylab.ylim(-5, 3)

pylab.show()

Edit: I agree with @tcaswell. You should use the pyplot package instead:

import numpy as np
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7]
y = [2, 3, 4, 5, 6, 7, 8]

plt.plot(x, y)
plt.axhline(0, color="black")
plt.axvline(0, color="black")

plt.xlim(-5, 3)
plt.ylim(-5, 3)

plt.show()
  • 4
    Don't use `pylab`, use `pyplot` instead (pylab is just a cluttered namespace). And you _should_ be using the OO interface anyway. – tacaswell Jul 05 '14 at 03:43
  • @tcaswell Thanks for the tip! I'm just starting with matplotlib :-) – cdonts Jul 05 '14 at 14:55