matplotlib的使用——secondary axis次坐标轴的使用

次坐标轴显示的常用函数

plt.subplots()

plt.subplots()是一个函数,返回一个包含figure和axes对象的元组。
因此,使用fig,ax = plt.subplots()将元组分解为fig和ax两个变量。

plt.subplots(
	nrows=1, 
	ncols=1, 
	sharex=False,
	sharey=False, 
	squeeze=True,
    subplot_kw=None, 
    gridspec_kw=None, 
    **fig_kw)

其中常用参数为:
nrows,ncols:代表子图的行列数。
sharex, sharey:

    设置为 True 或者 ‘all’ 时,所有子图共享坐标轴
     设置为 False or ‘none’ 时,所有子图的坐标轴独立
     设置为 ‘row’ 时,每一行的子图会共享坐标轴
     设置为 ‘col’ 时,每一列的子图会共享坐标轴

https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots.html
具体使用方式可以参考
下面两种表达方式具有同样的效果:

fig = plt.figure()
ax1 = fig.add_subplot(111)

fig,ax1 = plt.subplots()

作用相当于添加一幅图像,并在其中添加一个坐标轴。
在这里插入图片描述

ax1.twinx()

用于将ax1的x轴镜像对称。

fig,ax1 = plt.subplots()

# 画出ax1的x轴对称镜像
ax2 = ax1.twinx()

效果为:
在这里插入图片描述

应用示例

最终将实现如下效果:
在这里插入图片描述

实现代码为:

import numpy as np
import matplotlib.pyplot as plt

x = [1,2,3,4,5,6,7]
y1 = [1,2,3,4,5,6,7]
y2 = [-1,-2,-3,-4,-5,-6,-7]

fig,ax1 = plt.subplots()

# 画出ax1的x轴对称镜像
ax2 = ax1.twinx()

ax1.plot(x,y1,'g--')
ax2.plot(x,y2,'b--')

ax1.set_ylabel("y1",color = 'g')
ax2.set_ylabel("y2",color = 'b')

# 标记1
x0 = x[1]
y0 = y1[1]
ax1.scatter(x0,y0,s = 50,color = 'green')
ax1.annotate('y1',xy=(x0,y0),xycoords='data',xytext = (+30,-30),textcoords = 'offset points',
    fontsize = 16,arrowprops=dict(arrowstyle = '->',connectionstyle = 'arc3,rad=0.2'))

# 标记2
x0 = x[1]
y0 = y2[1]
ax2.scatter(x0,y0,s = 50,color = 'green')
ax2.annotate('y2',xy=(x0,y0),xycoords='data',xytext = (+30,-30),textcoords = 'offset points',
    fontsize = 16,arrowprops=dict(arrowstyle = '->',connectionstyle = 'arc3,rad=0.5'))
plt.show()
posted @ 2021-12-13 11:19  wuyuan2011woaini  阅读(411)  评论(0编辑  收藏  举报