1

So I am working on a program that displays the graph of a function over an interval, and the plot size is automatically handled by matplotlib. The only thing is, it resizes without showing x=0 and y=0 cartesian axes. Everything I tried so far, like plt.subplot(), only affects the axes that show at the bottom and left, not the cartesian axes. Is there a way to add the axes in?

Here is some example code:

import matplotlib.pyplot as plt
import numpy as np


x = np.linspace(-2, 1, 100)
f = lambda x: x**2 - 1
plt.plot(x, f(x))
plt.show()

The graph that comes from this looks like this: enter image description here

which does not show the cartesian axes. Is there a way to add this in, maybe by adding lines at x=0 and y=0?

Yaho Muse
  • 45
  • 7

2 Answers2

2

You can set the spine axis to be in a custom position, like the origin:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-2,1,100)
y = x**2

fig, ax = plt.subplots(1, figsize=(6, 4))
ax.plot(x, y)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')

ax.set(ylim=(-1, 4))

enter image description here

Otherwise, you can add a vertical and a horizontal line:

fig, ax = plt.subplots(1, figsize=(6, 4))
ax.plot(x, y)
ax.axhline(0, color='black')
ax.axvline(0, color='black')

enter image description here

Andrea
  • 2,932
  • 11
  • 23
0

You can do it by drawing arrows:

import matplotlib.pyplot as plt
import numpy as np
from pylab import *


x = np.linspace(-2, 1, 100)
f = lambda x: x**2 - 1


fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_aspect('equal')
plt.plot(x, f(x))

l,r = ax.get_xlim()
lo,hi = ax.get_ylim()
arrow( l-1, 0, r-l+2, 0, length_includes_head = False, head_width = 0.2 )
arrow( 0, lo-1, 0, hi-lo+2, length_includes_head = True, head_width = 0.2 )
plt.show()

enter image description here

Amin Gheibi
  • 639
  • 1
  • 8
  • 15