坐标轴设置
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IloVMccX-1648619788804)(attachment:image.png)]](https://i-blog.csdnimg.cn/blog_migrate/500f9fb768cc36c85a88e98dfb480354.png)
左边的视图里有四条边,称为视图的spine——脊柱。如何对spine操作得到右图的效果?
① 去除上面和右面的spine;
②再把左面的spine移至中间;
③ 再把下面的spine 向上移,使得两个0值重合
所有对spine的操作均在 gca() 方法中完成, gca——get current axes
x = np.linspace(-50, 51)
y = x**2
plt.plot(x, y)

获取当前坐标轴
plt.plot(x, y)
axes = plt.gca()

通过坐标轴 spines 确定 top bottom left right 四个轴
因为我们不需要上方和右方的spine 所以把颜色设置为空
plt.plot(x, y)
axes = plt.gca()
axes.spines['right'].set_color('none')
axes.spines['top'].set_color('none')
axes

plt.plot(x, y)
axes = plt.gca()
axes.spines['right'].set_color('none')
axes.spines['top'].set_color('none')
# 移动轴的方式有多种 data 传入的数据就是目标位置的值
# 第二种方式:通过 axes 属性移动 因为我们要移动的是垂直的轴 0.5的含义就是移动的距离是水平轴长度的百分比
# axes.spines['left'].set_position(('data', 0.0))
axes.spines['left'].set_position(('axes', 0.5))
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jD3msAVr-1648619788807)(output_13_0.png)]
再通过同样的方法把bottom 的轴 往上移动
plt.plot(x, y)
axes = plt.gca()
axes.spines['right'].set_color('none')
axes.spines['top'].set_color('none')
axes.spines['left'].set_position(('axes', 0.5))
axes.spines['bottom'].set_position(('data', 0.0))
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-G9w5YYAx-1648619788808)(output_15_0.png)]
设置轴的区间
plt.plot(x, y)

plt.ylim(-500, 3000)
plt.xlim(-60, 61)
plt.plot(x, y)

也可以动态设置
plt.ylim(y.min(), y.max())
plt.xlim(-60, x.max())
plt.plot(x, y)

本文介绍如何使用Matplotlib定制坐标轴样式,包括隐藏顶部和右侧坐标轴、调整左侧坐标轴位置至中间、移动底部坐标轴使其与左侧坐标轴的0值对齐,以及设置坐标轴显示范围。

3077

被折叠的 条评论
为什么被折叠?



