Matplotlib之设置x,y坐标轴的位置

  • 先将显示的坐标图的上边框和右边框去掉,即设置它们的显示方式为不显示:
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

 注:spines译为‘脊’,也就是坐标图中的边框。

  • 将坐标图的下边框和左边框作为坐标系的x轴和y轴,并调整坐标轴的位置:
ax.spines['bottom'].set_position(('data',0))  #data表示通过值来设置x轴的位置,将x轴绑定在y=0的位置
ax.spines['left'].set_position(('axes',0.5))  #axes表示以百分比的形式设置轴的位置,即将y轴绑定在x轴50%的位置,也就是x轴的中点

注:设置坐标轴的位置时,‘data’表示通过值来设置坐标轴的位置, ax.spines['bottom'].set_position(('data',0))表示将x轴设置在y=0处。'axes'表示以百分比的形式设置轴的位置,ax.spines['bottom'].set_position(('axes',0.3))表示将x轴设置在y轴范围的30%处。除了‘data’、‘axes’属性,还有一个‘outward’属性可以来设置坐标轴的位置,这个属性我还没有用过。

例子: 

import matplotlib.pyplot as plt
from numpy import *
x=linspace(-2,2)
y=2*x+1
plt.xlim(-2,2)
plt.ylim(-3,5)

ax=plt.gca()  #gca:get current axis得到当前轴
#设置图片的右边框和上边框为不显示
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

#挪动x,y轴的位置,也就是图片下边框和左边框的位置
ax.spines['bottom'].set_position(('data',0))  #data表示通过值来设置x轴的位置,将x轴绑定在y=0的位置
ax.spines['left'].set_position(('axes',0.5))  #axes表示以百分比的形式设置轴的位置,即将y轴绑定在x轴50%的位置,也就是x轴的中点

plt.plot(x,y)
plt.show()     #显示

运行结果:

Matplotlib之设置x,y坐标轴的位置_第1张图片

 

 

你可能感兴趣的:(python,Matplotlib)