Python matlpotlib 绘图汇总

本文介绍了Matplotlib库中plt、figure和ax的关系,plt作为工具箱创建figure和ax,figure为最外层容器,ax用于绘制具体图形。示例展示了如何创建和操作ax对象以及如何绘制高斯函数,包括计算全高宽度和sigma。
摘要由CSDN通过智能技术生成

figure、plt、ax的关系

  • plt是Matplotlib中最常用的模块,用于绘制图形,可以理解为绘图工具箱,可以通过plt中的函数创建figure和ax;
  • figure是Matplotlib中的最外层容器,一个figure可以包含多个ax,即多个子图;
  • ax是一个subplot,即子图,是figure中的一个区域,用于绘制具体的图形。
import matplotlib.pyplot as plt
import numpy as np

# 定义一个二维数组
data = np.random.randn(100, 5)

# 定义一个ax对象
fig, ax = plt.subplots()

# 定义一个绘图函数,将数据绘制成折线图并添加到指定的ax对象中
def plot_data(data, ax):
    # 绘制折线图
    ax.plot(data)

    # 设置x轴和y轴标签
    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')

    # 设置标题
    ax.set_title('Line Plot')
def plot_data1(data, ax):
    # 绘制折线图
    ax.plot(data + 1)

    # 设置x轴和y轴标签
    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')

    # 设置标题
    ax.set_title('Line Plot')
# 调用plot_data函数绘制图形
plot_data(data, ax)
plot_data1(data, ax)

# 显示图形
plt.show()

我先使用fig, ax = plt.subplots(),之后再用plt会有什么影响

在使用fig, ax = plt.subplots()创建一个figure和一个Axes对象后,你可以使用ax对象上的各种方法来绘制图形。如果你在之后使用了plt方法,那么它会在当前活动的figure对象上创建子图,而不是之前定义的ax对象上的子图。这意味着,使用plt方法可能会影响到你之前在ax对象上绘制的图形。

例如,如果你在使用fig, ax = plt.subplots()创建的ax对象上绘制了一个散点图,然后在之后使用plt.plot方法创建了一条曲线,那么这条曲线会被添加到同一个figure对象上,但会覆盖掉之前的散点图。

fig.add_subplot方法或plt.subplots有什么区别

  • fig.add_subplot方法和plt.subplots方法都可以用于在figure对象上创建一个或多个子图,它们之间的主要区别在于调用方式和返回结果。
  • fig.add_subplot方法通过在figure对象上创建新的Axes对象来添加子图,返回一个Axes对象,你可以使用它来绘制子图,提供了更多的灵活性和控制。
  • plt.subplots方法则是创建一个figure对象,并返回一个包含figure对象和Axes对象的元组,可以一次性创建多个子图,更为简单,但相对灵活性较低。根据你的需求,你可以选择使用其中任何一个方法。

填充图形

import numpy as np
import matplotlib.pyplot as plt

# 定义高斯函数
def gaussian(x, mu, sigma):
    return np.exp(-(x - mu)**2 / (2 * sigma**2)) / (sigma * np.sqrt(2 * np.pi))

# 定义左边高斯函数的参数
mu1 = 5   # 均值
sigma1 = 1   # 标准差

# 定义右边高斯函数的参数
mu2 = 12  # 均值
sigma2 = 3   # 标准差

# 计算交叉点的位置
x0 = (mu1 * sigma2**2 + mu2 * sigma1**2) / (sigma1**2 + sigma2**2)

# 绘制左边高斯函数的图像
x_left = np.linspace(0, x0+5, 1000)
y_left = gaussian(x_left, mu1, sigma1)
plt.plot(x_left, y_left, 'b-', label='noise')

# 绘制右边高斯函数的图像
x_right = np.linspace(x0-2, 20, 1000)
y_right = gaussian(x_right, mu2, sigma2)
plt.plot(x_right, y_right, 'r-', label='signal')

# 绘制交叉点处的虚线
plt.axvline(x=x0, color='k', linestyle='--')
# 绘制左边高斯函数的 x 至无穷的部分并加阴影
x_left_shaded = np.linspace(x0, 10, 1000)
y_left_shaded = gaussian(x_left_shaded, mu1, sigma1)
plt.fill_between(x_left_shaded, y_left_shaded, alpha=0.2,color='blue')



# 添加图例、标题和坐标轴标签
plt.legend()
plt.title('Probability density distribution')
plt.xlabel('Amplitude')
plt.ylabel('Frequency')

# 显示图像
plt.show()

在这里插入图片描述
高斯函数计算(半高宽计算sigma)

import numpy as np
import matplotlib.pyplot as plt

# 定义高斯函数
def gaussian(x, u, sigma, A):
    return A * np.exp(-0.5 * ((x - u) / sigma) ** 2)



# 设置图像大小
fig, ax = plt.subplots(figsize=(8, 6))

# 定义函数参数
FWHM = 10  # 全高宽度
A = 5      # 峰值

# 计算标准差
sigma = FWHM / (2 * np.sqrt(2 * np.log(2)))

# 计算x的范围
u = 10  # 均值
x_min = u - 4 * sigma
x_max = u + 4 * sigma
x = np.linspace(x_min, x_max, 1000)

# 画出高斯函数曲线
y = gaussian(x, u, sigma, A)
ax.plot(x, y, color='blue')

# 计算全高宽度的两端点
left_fwhm = u - FWHM/2
right_fwhm = u + FWHM/2
y_fwhm = gaussian(left_fwhm, u, sigma, A)

# 绘制全高宽度的线段
ax.plot([left_fwhm, right_fwhm], [y_fwhm, y_fwhm], color='red', linestyle='--')
ax.plot([left_fwhm, right_fwhm], [y_fwhm, y_fwhm],  'o',color='red')
ax.annotate(f'FWHM = {FWHM:.2f}', xy=(u - FWHM/2, y_fwhm), xytext=(u - 2.5*sigma, A/1.2),
            arrowprops=dict(arrowstyle='-|>', color='red'),fontsize=14)

# 画出左右两侧趋近于0的拐点
left_edge = u - 3 * sigma
right_edge = u + 3 * sigma
y_edge = gaussian(left_edge, u, sigma, A)
ax.plot([left_edge, right_edge], [y_edge, y_edge], color='green', linestyle='--')
ax.plot([left_edge, right_edge], [y_edge, y_edge], 'o',color='green')

ax.axvline(x=left_edge, color='green', linestyle='--')
ax.axvline(x=right_edge, color='green', linestyle='--')

# ax.annotate(f'${2*3*sigma:.2f}$', xy=(u, 0), xytext=(u - 3.5*sigma, A/5),
#             arrowprops=dict(arrowstyle='->', color='green', linewidth=1.5, connectionstyle="arc3,rad=.2"))

ax.annotate(f'6σ = {2*3*sigma:.2f}', xy=(left_edge, y_edge), xytext=(u - 4*sigma, A/4),
            arrowprops=dict(arrowstyle='-|>', color='green', linewidth=1.5),fontsize=14)

# 添加坐标轴标签和标题
ax.set_xlabel('time(ns)', fontsize=16)
ax.set_ylabel('Number of photon', fontsize=16)
ax.set_title('The Gaussian distribution of photon', fontsize=18)

# 显示图像
plt.show()

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值