分享

如何设置matplotlib中x,y坐标轴的位置?

 老马的程序人生 2021-05-22

在机器学习中经常会使用Sigmoid函数,如果直接使用matplotlib绘图,那么就会像下图这样,原点并没有在(0,0)。

import matplotlib.pyplot as plt
import numpy

x = numpy.linspace(start=-10, stop=10)
y = 1 / (1 + numpy.e ** (-1 * x))

plt.plot(x, y)
plt.title('Sigmoid')
plt.show()

于是,我们希望调整坐标轴的位置,让图像更加的直观。

在matplotlib的图中,默认有四个轴,两个横轴(“top”、“bottom”)和两个竖轴(“left”、“right”),可以通过ax = plt.gca()方法获取,gca是“get current axes”的缩写。

先将显示的坐标图的上边框和右边框去掉,即设置它们的显示方式为不显示:

ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

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

将坐标图的下边框和左边框作为坐标系的x轴和y轴,并调整坐标轴的位置:

ax.spines['bottom'].set_position(('data'0))
ax.spines['left'].set_position(('axes'0.5))

注:设置坐标轴的位置时,“data”表示通过值来设置坐标轴的位置,“axes”表示以百分比的形式设置轴的位置。

  • ax.spines['bottom'].set_position(('data',0))表示将x轴设置在y=0处。
  • ax.spines['bottom'].set_position(('axes',0.3))表示将x轴设置在y轴范围的30%处。

完整代码如下:

import matplotlib.pyplot as plt
import numpy

x = numpy.linspace(start=-10, stop=10)
y = 1 / (1 + numpy.e ** (-1 * x))

ax = plt.gca() # 获取坐标轴

ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_position(('data'0))
ax.spines['left'].set_position(('axes'0.5))

plt.plot(x, y)
plt.title('Sigmoid')
plt.show()

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多