python 中matplotlib 实现多个坐标轴画图


一、实现结果

下面是图片是我实现的一个结果,里面包含两个坐标系。

在这里插入图片描述

如果想要实现更多坐标系,请看下面第 第四节 解释。

二、定义画图函数

我将画出的图像的代码部分封装到一个画图函数中,这样将来用到其他的代码中,便于实现。

def draw_function(x1_vals, y1_vals, x2_vals,y2_vals,x_label):

    plt.subplot(2,1,1)
    plt.xlabel(x_label)
    plt.ylabel('Sin')
    plt.plot(x1_vals, y1_vals,'-*')
    plt.legend(['sin'])

    plt.subplot(2,1,2)
    plt.xlabel(x_label)
    plt.ylabel('Cos')
    plt.plot(x2_vals, y2_vals, color='g',linestyle='-.')
    plt.legend(['cos'])

    plt.show()

三、完整代码

import matplotlib.pyplot as plt
import numpy as np


def draw_function(x1_vals, y1_vals, x2_vals,y2_vals,x_label):

    plt.subplot(2,1,1)
    plt.xlabel(x_label)
    plt.ylabel('Sin')
    plt.plot(x1_vals, y1_vals,'-*')
    plt.legend(['sin'])

    plt.subplot(2,1,2)
    plt.xlabel(x_label)
    plt.ylabel('Cos')
    plt.plot(x2_vals, y2_vals, color='g',linestyle='-.')
    plt.legend(['cos'])

    plt.show()


x = np.linspace(0, 4* np.pi, 50)
y1 = np.sin(x)
y2 = np.cos(x)


draw_function(x,y1,x,y2,'x',)

四、实现四个坐标系

1.代码解释

plot.subplot(x,y,z)

上面的括号里面字母分表代表 XY代表的坐标轴总共有XY列,所以最后总共有 X乘Y个坐标轴,Z代表的是坐标轴为第几个。

2.实现结果

在这里插入图片描述

五、进阶版

实现各个坐标图,重点标注单位内Y轴数值异常变化

1. 效果

在这里插入图片描述

2. 源码

import matplotlib.pyplot as plt
import numpy as np


def draw_function(x, data):
    # 绘制坐标图每个子坐标图对应标签以及单位注明
    label_dict = [['sin', 'cos'], ['power', 'exp']]
    unit = [['hours', 'min'], ['s', 'ms']]

    fig, axes = plt.subplots(len(label_dict), len(label_dict[0]), figsize=(len(label_dict[0])*7, len(label_dict)*3))

    for i in range(len(label_dict)):
        for j in range(len(label_dict[0])):
            label = label_dict[i][j]
            y_value = data[label][:]

            # 高亮点计算
            differences = np.abs(np.diff(y_value))
            hight_x = []
            hight_y = []
            for k in range(len(differences)):
                if differences[k] > changeTH:
                    hight_x.append(x[k + 1])
                    hight_y.append(y_value[k + 1])
                    hight_x.append(x[k])
                    hight_y.append(y_value[k])

            axes[i][j].plot(x, y_value, label=label)
            axes[i][j].scatter(hight_x, hight_y, color='red', zorder=5)
            axes[i][j].set_ylabel(unit[i][j])
            axes[i][j].legend([label], loc='lower right')
            axes[i][j].set_title(label)

    plt.xticks(x)
    plt.tick_params(axis='both', labelsize=15)
    plt.suptitle('[TITLE: This is a 4*4 subplots.]')  # 整个大图标题
    plt.tight_layout()
    plt.savefig('1.png')

    print(f"折线图生成!")
    # plt.show()
    plt.close()


if __name__ == '__main__':
    changeTH = 5
    x = np.linspace(0, 4 * np.pi, 50)
    data = {
        'sin': 10 * np.sin(x),
        'cos': 10 * np.cos(x),
        'power': np.power(x, 2),
        'exp': np.exp(x)
    }
    draw_function(x, data)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值