栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

Matplotlib多y轴绘制

01 引言:

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

02 结果如下:

03 代码如下:
# -*- encoding: utf-8 -*-
'''
@File    :   n axis.py
@Time    :   2022/06/12 13:44:01
@Author  :   HMX 
@Version :   1.0
@Contact :   kdhb8023@163.com
'''

# 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()

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/968423.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号