Skill - Centering the plot axes in matplotlib
Skills Required
- Setup python development environment
- Basic Printing in Python
- Commenting in Python
- Managing Variables in python
- Introduction to Matplotlib plotting library
- Styling Matplotlib plots
Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision
Matplotlib is a plotting library tn the scipy ecosystem of libraries.
Please make sure that you covered the post on basics
Sometimes we may require to have the main axis lines to be intersecting at (0,0) of the subplot. We will control the positioning of spines
to achieve this.
import matplotlib.pyplot as plt
x = [-5, -4, 5, 8]
y = [-6, 5, 8,-10]
# create a plotting area and get the figure, axes handle in return
fig, ax = plt.subplots()
# plot data on the axes handle
ax.plot(x, y)
# Move left y-axis and bottim x-axis to centre by setting position as 'center'
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
# Eliminate top and right axes by setting spline color as 'none'
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# print the plot
plt.show()
As shown above the spines/axis lines of an axes handle ax
can be controlled by ax.spines
If we want the axis lines to be intersecting at center of the subplot instead of (0,0).
In such case we can use the following
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
The output would be like the image below
Video
You can the video on this post here
Online Interpreter
Although we recommend to practice the above examples in Visual Studio Code, you can run these examples online at https://pynative.com/online-python-code-editor-to-execute-python-code/
References
- Solution from stackoverflow post - https://stackoverflow.com/questions/31556446/how-to-draw-axis-in-the-middle-of-the-figure
- Spine placement demo - https://matplotlib.org/3.1.0/gallery/ticks_and_spines/spine_placement_demo.html
Comments
Post a Comment