python使用matplotlib库绘制散点图,总结的封装方法

使用python语言,matplotlib库绘制散点图,总结了四种图像,并一一封装成了方法,直接调用使用。

先安装matplotlib库

pip install matplotlib

 代码如下:

import random
from typing import Sequence
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
from matplotlib.colors import LinearSegmentedColormap

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


def simplePoint(ax: plt.Axes, xs: Sequence, ys: Sequence):
    """绘制简单的散点图"""
    ax.scatter(xs, ys, marker='+', color='red')
    ax.set_title('simple point chart')


def point3d(ax: plt.Axes, position: (int, int, int), xs: Sequence, ys: Sequence, zs: Sequence):
    """绘制三维散点图"""
    ax.remove()
    # projection='3d' 代表三维图像, elev=30 仰角, azim=45 方位角
    ax = fig.add_subplot(*position, projection='3d', elev=30, azim=45, )
    ax.scatter(xs, ys, zs)
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')
    ax.set_title('3D point chart')


def sizePoint(ax: plt.Axes, xs: Sequence, ys: Sequence, sizes: Sequence):
    """绘制带尺寸的散点图"""
    cmap = LinearSegmentedColormap.from_list('my_cmap', ['red', 'yellow', 'green'])
    colors = cmap(np.arange(cmap.N))[::int(256 / len(xs))][0:len(xs)]
    ax.scatter(xs, ys, s=sizes, c=colors, alpha=0.5)
    ax.set_title('size point chart')
    ax.grid()


def polarPoint(ax: plt.Axes, position: (int, int, int), thetas: Sequence, rs: Sequence, sizes: Sequence):
    """极坐标带尺寸的散点图"""
    ax.remove()
    ax = fig.add_subplot(*position, polar=True)
    cmap = LinearSegmentedColormap.from_list('my_cmap', ['red', 'yellow', 'green'])
    colors = cmap(np.arange(cmap.N))[::int(256 / len(thetas))][0:len(thetas)]
    ax.scatter(thetas, rs, s=sizes, c=colors, alpha=0.5)
    ax.set_title('polar size point chart')


if __name__ == '__main__':
    x = list(range(100))
    y = list(range(100))
    z = list(range(100))
    random.shuffle(x)
    random.shuffle(y)
    random.shuffle(z)

    fig, axs = plt.subplots(2, 2)
    simplePoint(axs[0][0], x, y)
    point3d(axs[0][1], (2, 2, 2), x, y, z)  # position:(2,3,4),表示在2×3网格中的第4个位置
    sizePoint(axs[1][0], x, y, z)
    polarPoint(axs[1][1], (2, 2, 4), x, y, z)

    plt.show()

结果图

使用时只需根据需要更改数据即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值