用python生成带有坐标轴的二维高斯分布散点图

  • Post author:
  • Post category:python




0.引言

该代码用于生成一个带坐标轴的二维高斯分布散点图,使用前请确保自己安装了numpy、matplotlib、mpl_toolkits模块。



1.np.random.multivariate_normal

该函数用于生成二维高斯分布的散点,其参数为

def multivariate_normal(mean, cov, size=None, check_valid=None, tol=None) 

其中mean表示样本均值,cov为样本的

协方差矩阵

,size代表需要生成的样本点个数,当需要生成二维的高斯分布时,mean传入的参数是一个1*2的数组,其中第一个值和第二个值代表x轴和y轴上的样本均值。



2.代码

import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist

if __name__ == '__main__':
    mean = np.array([0, 0])
    cov = np.array([[10, 0], [0, 2]])

    #生成高斯分布
    data = np.random.multivariate_normal(mean, cov, 1000)
    x, y = data.T

    fig = plt.figure(figsize=(8, 8))
    ax = axisartist.Subplot(fig, 111)
    fig.add_axes(ax)

    # 通过set_visible方法设置绘图区所有坐标轴隐藏
    ax.axis[:].set_visible(False)

    # ax.new_floating_axis代表添加新的坐标轴
    ax.axis["x"] = ax.new_floating_axis(0, 0)
    # 给x坐标轴加上箭头
    ax.axis["x"].set_axisline_style("->", size=1.0)
    # 添加y坐标轴,且加上箭头
    ax.axis["y"] = ax.new_floating_axis(1, 0)
    ax.axis["y"].set_axisline_style("-|>", size=1.0)
    # 设置x、y轴上刻度显示方向
    ax.axis["x"].set_axis_direction("top")
    ax.axis["y"].set_axis_direction("right")

    plt.scatter(x, y, s=15)
    plt.axis()
    plt.xlim(-10, 10)
    plt.ylim(-10, 10)
    plt.xlabel("x")
    plt.ylabel("y")
    plt.show()



3.运行结果
在这里插入图片描述



4.参考


Python-matplotlib绘制带箭头x-y坐标轴图形



版权声明:本文为qq_41997070原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。