python使用matplotlib库绘制折线图,封装出的方法

使用python语言,matplotlib库绘制散点图,总结了五种图像,包括简单折线图、多条折线图、极轴折线图、堆叠折线图、茎图,并一一封装成了方法,直接调用使用。

先安装matplotlib库

pip install matplotlib

代码如下:

from typing import Sequence
import matplotlib.pyplot as plt
import matplotlib

matplotlib.use('TkAgg')
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


def simpleLine(ax: plt.Axes, xs: Sequence, ys: Sequence):
    """绘制简单的折线图"""
    ax.plot(xs, ys, marker='+', linewidth=1, )
    ax.set_xlabel("x")
    ax.set_ylabel("y")
    ax.grid()
    ax.set_title("simple line chart")


def multipleLine(ax: plt.Axes, xs: Sequence, yss: Sequence[Sequence]):
    """多条折线图"""
    markers = ['o', '+', 'x', '*', 's', 'd']
    for index, ys in enumerate(yss):
        ax.plot(xs, ys, linewidth=1, marker=markers[index], label=f'line-{index}')
    ax.set_xlabel("x")
    ax.set_ylabel("y")
    ax.grid()
    ax.legend(title="legend")
    ax.set_title("multiple line chart")


def stackLine(ax: plt.Axes, xs: Sequence, yss: Sequence[Sequence]):
    """堆栈折线图"""
    labels = list(f"line-{i}" for i in range(len(yss)))
    ax.stackplot(xs, yss, labels=labels, alpha=0.8)
    ax.legend(reverse=True)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.grid()
    ax.set_title('stack line chart')


def stemLine(ax: plt.Axes, xs: Sequence, ys: Sequence, bottom):
    """茎图"""
    ax.stem(xs, ys, bottom=bottom, markerfmt='D', linefmt='blue')
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.grid()
    ax.set_title('stem line chart')

def polarLine(ax: plt.Axes, position: (int, int, int), thetas: Sequence, rs: Sequence):
    """极坐标折线图"""
    ax.remove()
    ax = fig.add_subplot(*position, polar=True)
    ax.plot(thetas, rs, marker='o', linewidth=1)
    ax.set_xlabel('theta')
    ax.set_ylabel('r')
    ax.set_title('polar line chart')

if __name__ == '__main__':
    x = [1, 2, 3, 4, 5, 6, 7, 8]
    y1 = [3, 5, 4, 8, 10, 12, 11, 14]
    y2 = [[1, 2, 4, 4, 5, 6, 8, 10],
          [2, 4, 5, 9, 10, 12, 15, 11],
          [3, 6, 8, 14, 17, 19, 22, 20]]

    fig, axs = plt.subplots(2, 3)
    simpleLine(axs[0][0], x, y1)
    multipleLine(axs[0][1], x, y2)
    stackLine(axs[1][0], x, y2)
    stemLine(axs[1][1], x, y1, 6)
    polarLine(axs[0][2], (2, 3, 3), x, y1)

    plt.show()

效果图如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值