import numpy as np
import matplotlib.pyplot as plt
# 确定横坐标范围
x = np.linspace(-np.pi, np.pi, 300)
# 定义函数
y = np.cos(x)
# 绘制图形
plt.plot(x, y)
# 显示图像
plt.show()
绘制余弦曲线的代码在 Pycharm 中执行调用,执行的结果会弹出一个独立的桌面端图形界面。这里以二维图形为例,在 matplotlib 中的图形是由几个部分构成,如果想要更好的理解 matplotlib 模块,清楚这几个部分尤为的重要。由于本文主要介绍边框,因此只介绍与之相关的部分。
其中:
通过上图可以看出其实所谓的刻度线是依附在边框上面的,我们可以指定刻度线依附在那个位置的边框上。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 300)
y = np.cos(x)
plt.plot(x, y)
ax = plt.gca()
# x 刻度线参数:[ 'top' | 'bottom' | 'both' | 'default' | 'none' ]
ax.xaxis.set_ticks_position('top')
# y 刻度线参数:[ 'left' | 'right' | 'both' | 'default' | 'none' ]
ax.yaxis.set_ticks_position('right')
plt.show()
② axes 表示画纸,如果画板足够大,我们可以在画板上放置多张画纸,而在 matplotlib 中画板就是 figure,所以在一个 figure 画板中可以放置多个 axes 画纸。如果你要对画纸进行一些配置操作,就需要先告诉程序你要对那张画纸进行操作,如果画纸多我们可以进行指定,如果只有一个画纸我们只需要使用下面这个方法来获得当前的画纸。
# 获取当前 axes 类实例,gca 的英文全称 get current axes
ax = plt.gca()
有了需要进行配置的画纸,接下来就可以通过画纸来操作边框。边框操作由spines
进行管理,spines
方法提供了(top、bottom、left、right)四个方向边框的配置功能。
ax = plt.gca() # 获取当前画纸
>>> print(ax.spines)
OrderedDict([
('left', <matplotlib.spines.Spine object at 0x0000028F3723E400>),
('right', <matplotlib.spines.Spine object at 0x0000028F3723E518>),
('bottom', <matplotlib.spines.Spine object at 0x0000028F3723E630>),
('top', <matplotlib.spines.Spine object at 0x0000028F3723E748>)
])
通过输出结果可以看出,spines
将top、bottom、left、right四个方向的边框通过类似字典的方式进行存储,如果我们想要获取指定方式的边框,只需要使用类似 Python 字典的方式进行访问。获取到了这些边框,接下来就可以单独的进行更改设置了。下面给出几个常用的spines
函数:
函数 | 功能 |
---|---|
set_color(color) | 设置边框颜色,参数为颜色,默认为 None |
set_linewidth(width) | 设置边框的宽度 |
set_visible(bool) | 是否显示边框,参数为 True 或 False |
set_position(position) | 设置边框的位置 |
set_color
、set_visible
和set_linewidth
三个方法比较简单:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 300)
y = np.cos(x)
plt.plot(x, y)
ax = plt.gca()
# 将左边框设置为红色并指定宽度
ax.spines['left'].set_color('red')
ax.spines['left'].set_linewidth(2)
# 将下边框设置为蓝色
ax.spines['bottom'].set_color('blue')
# 将右边框以及上边框隐藏
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.show()
set_position(position)
函数稍微有点复杂,其中的 position 参数可以为:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 300)
y = np.cos(x)
plt.plot(x, y)
ax = plt.gca()
# 设置左边框的位置
ax.spines['left'].set_position(('outward', 10))
# 设置下边框的位置
ax.spines['bottom'].set_position(('axes', 0.5))
# ax.spines['bottom'].set_position('center')
# 设置右边框的位置
ax.spines['bottom'].set_position(('data', 0.0))
# ax.spines['bottom'].set_position('zero')
plt.show()
最常见的就是将坐标轴移动到数据的中心:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 300)
y = np.cos(x)
plt.plot(x, y)
ax = plt.gca()
# 隐藏上边框和右边框
# 将颜色设置为空也能达到隐藏效果
ax.spines['top'].set_color(None)
ax.spines['right'].set_visible(False)
# 将左边框和下边框移动到数据的中心位置
ax.spines['bottom'].set_position(('data', 0.0))
ax.spines['left'].set_position('center')
plt.show()