【Python基础绘图】多y轴绘制

Matplotlib多y轴绘制

【Python基础绘图】多y轴绘制_第1张图片

01 引言:

当多个y值对应同一x值时,可以借助多y轴完美解决,现记录分享一下matplotlib多y轴折线图绘制方法。

02 结果如下:

【Python基础绘图】多y轴绘制_第2张图片

03 代码如下:

# -*- encoding: utf-8 -*-
'''
@File    :   n axis.py
@Time    :   2022/06/12 13:44:01
@Author  :   HMX 
@Version :   1.0
@Contact :   [email protected]
'''

# here put the import lib
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

def cm2inch(x,y):
    return(x/2.54,y/2.54)

# 构造数据
x = np.arange(1,10)
y1 = x
y2 = x**2
y3 = x**3
y4 = x**4

# 构造多个ax
fig,ax1 = plt.subplots(figsize = cm2inch(16,9))
ax2 = ax1.twinx()
ax3 = ax1.twinx()
ax4 = ax1.twinx()

# 将构造的ax右侧的spine向右偏移
ax3.spines['right'].set_position(('outward',60))
ax4.spines['right'].set_position(('outward',120))

# 绘制
img1, = ax1.plot(x,y1,c = 'tab:blue')
img2, = ax2.plot(x,y2,c = 'tab:orange')
img3, = ax3.plot(x,y3,c = 'tab:green')
img4, = ax4.plot(x,y4,c = 'tab:red')

#获取对应折线图颜色给到spine ylabel yticks yticklabels
axs = [ax1,ax2,ax3,ax4]
imgs = [img1,img2,img3,img4]
for  i in range(len(axs)): 
    axs[i].spines['right'].set_color(imgs[i].get_color())
    axs[i].set_ylabel('y{}'.format(i+1),c = imgs[i].get_color())
    axs[i].tick_params(axis = 'y', color = imgs[i].get_color(), labelcolor = imgs[i].get_color())
    axs[i].spines['left'].set_color(img1.get_color())#注意ax1是left
# 设置其他细节
ax1.set_xlabel('x')
ax1.set_ylim(0,10)
ax2.set_ylim(0,100)
ax3.set_ylim(0,1000)
ax4.set_ylim(0,10000)
plt.tight_layout()
plt.savefig('n axis.png',dpi = 600)
plt.show()

​如果对你有帮助的话,请‘点赞’、‘收藏’,‘关注’,你们的支持是我更新的动力。
欢迎关注公众号【森气笔记】。

你可能感兴趣的:(python,matplotlib可视化,python,机器学习,开发语言)