MATPLOTLIB - Alignment of axis and functions according to custom boundaries provided by user

Viewed 45

I would like to know how to use matplotlib to graph functions similar to how it would be done in Desmos:

  • With the graph centered at the center of the screen

  • With axis centered at the center of the screen

  • With the function being graphed relative to the center of the screen (origin)

  • If possible, I would like to be able to set the boundaries of the axis

Desmos Graph Matplotlib Graph

My Current Code:

import matplotlib.pyplot as plt
import numpy as np

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

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_title('centered spines')

ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
1 Answers

Use set_position('zero') to have the spines centered on the origin.

If you want to origin centered on the screen, they you just have to set the axes limits so they are symmetric around zero:

import matplotlib.pyplot as plt
import numpy as np

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

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_title('centered spines')

ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

ax.plot(x,y)
ax.set_xlim(-100,100)
ax.set_ylim(-5000,5000)

enter image description here

Related