How can I draw axis lines inside a plot in Matplotlib?

谁说胖子不能爱 提交于 2021-01-27 04:07:58

问题


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.


回答1:


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')




回答2:


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.



来源:https://stackoverflow.com/questions/32606155/how-can-i-draw-axis-lines-inside-a-plot-in-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!