Home > Software engineering >  Python matplotlib draws curve outside axis by default?
Python matplotlib draws curve outside axis by default?

Time:12-07

Does Python matplotlib by default plot outside the axis if matplotlib.pyplot.xlim is applied?

This is the code I have written.

import matplotlib.pyplot as plt
import numpy as np

plt.figure()
x = np.linspace(-10, 10, 11)
y = x**2
plt.plot(x, y)
plt.xlim((-5, 5))

This is what I get: enter image description here

This is what I want: enter image description here

I am using matplotlib version 3.5.3 with Spyder IDE.

CodePudding user response:

Thank you for your reply. It made me try to disable inline graphics generation in Spyder. Now it works. I remember that a few days ago I made an anaconda update by using conda update --all. May be this changed something?

enter image description here

CodePudding user response:

It seems like 'clip_on' is setted to 'False'.

Try to set it to 'True' when you plot:

plt.plot(x, y, clip_on = True)

Another option is to clip your x and y before plotting:

import matplotlib.pyplot as plt
import numpy as np
plt.figure()
x = np.linspace(-10, 10, 11)
y = x**2
new_x = x[x>-5]
new_y = y[x>-5]
plt.plot(new_x[new_x<5], new_y[new_x<5], clip_on=False) #clip_on=False just for demonstration
plt.xlim((-5, 5))

Thats way, eventhough 'clip_on' is setted to 'False', there won't be data outside your grid.

matplotlib documentation for 'clip_on'.

  • Related