如何设置matplotlib中x,y坐标轴的位置?
发布日期:2021-06-30 22:51:44 浏览次数:3 分类:技术文章

本文共 1147 字,大约阅读时间需要 3 分钟。

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

import matplotlib.pyplot as pltimport numpyx = 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.5))表示将x轴设置在y轴范围的50%处。

完整代码如下:

import matplotlib.pyplot as pltimport numpyx = 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()

转载地址:https://lsgogroup.blog.csdn.net/article/details/117136838 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【第15周复盘】B站是个学习的网站
下一篇:Datawhale组队学习周报(第013周)

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月11日 20时08分13秒