12

When I plot data using Matplotlib, the axes are always plotted by default as a box framing the plot. Let's say I am plotting data within axis limits -2 < x < 2 and -2 < y < 2, but I would like to draw axis lines inside this plot area through the origin, preferably with ticks and tick labels along these axis lines - not along the outer frame.

2
  • When asking us to solve a problem that requires writing code, it is best to first give some example code, include the plot and tell us what exactly you would like to change. Telling us what you have already tried and did not work would be nice, but not necessary. Commented Sep 16, 2015 at 10:47
  • 3
    @cel: As someone who regularly deals with matplotlib, I think the question is quite clear. Commented Sep 16, 2015 at 10:50

2 Answers 2

15

This is well documented in the spines example (old link) / spine placement demo (new link).

You are going to turn off the right and top spines (e.g. spines['right'].set_color('none')), and move the left and bottom spines to the zero position (e.g. spines['left'].set_position('zero')).

import numpy as np
import matplotlib.pyplot as plt


fig = plt.figure()
x = np.linspace(-np.pi, np.pi, 100)
y = 2*np.sin(x)

ax = fig.add_subplot(111)
ax.set_title('zeroed spines')
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')

# remove the ticks from the top and right edges
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

10

I can at least give a half-complete answer. Yes, you can easily draw the axis lines. It is as simple as

plt.axvline(0)
plt.axhline(0)

The original axes will remain, but can be turned off with plt.axis('off'). It will also not give you any tick marks.

2 Comments

Thanks, that at least takes me some of the way. I will try to see if I can find a way of decorating those with ticks and labels.
I would suggest looking through the matplotlib documentation. There is quite a lot of things possible with matplotlib if you look past the matplotlib.pyplot module, and instead check the "real" API. Drawing the coordinate axes is something that I have wanted to do myself several times, but never had the time to completely solve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.