利用matplotlib的plot方法绘制高斯函数
时间: 2023-11-08 10:09:45 浏览: 200
可以使用以下代码绘制高斯函数:
```
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-3, 3, 0.1)
sigma = 1
y = np.exp(-x**2 / (2*sigma**2)) / (np.sqrt(2*np.pi) * sigma)
plt.plot(x, y)
plt.show()
```
其中,`x`为横坐标的取值范围,`sigma`为高斯分布的标准差,`y`为对应的纵坐标。将横纵坐标传入 `plt.plot` 方法中即可绘制高斯函数,调用 `plt.show` 可以显示图像。
相关问题
利用matplotlib的plot方法绘制高斯函数曲线图
好的,让我为您解答。要绘制高斯函数曲线图,需要先导入numpy和matplotlib库。接着,可以使用numpy库的exp函数和power函数来计算高斯分布的值,然后利用matplotlib库的plot方法绘制曲线图。以下是示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义高斯函数
def gaussian(x, mu, sigma):
return np.exp(-np.power(x - mu, 2) / (2 * np.power(sigma, 2)))
# 生成x轴数据
x = np.linspace(-5, 5, 100)
# 计算y轴数据
mu = 0 # 均值
sigma = 1 # 标准差
y = gaussian(x, mu, sigma)
# 绘制曲线图
plt.plot(x, y)
# 添加标题和标签
plt.title("Gaussian Distribution")
plt.xlabel("x")
plt.ylabel("y")
# 显示图像
plt.show()
```
这样就可以绘制出高斯函数曲线图了。希望对您有所帮助!
利用matplotlib绘制高斯函数和超高斯函数曲线图
### 高斯分布与超高斯分布的绘制
为了实现高斯分布和超高斯分布的可视化,可以基于 `matplotlib` 和 `numpy` 库完成。以下是详细的说明以及代码示例。
#### 1. 高斯分布 (Gaussian Distribution)
高斯分布的概率密度函数定义为:
\[
f(x|\mu,\sigma^2)= \frac{1}{\sqrt {2\pi}\sigma}e^{-{\frac {(x-\mu)^{2}}{2\sigma ^{2}}}}
\]
其中:
- \( \mu \) 是均值,
- \( \sigma \) 是标准差。
通过调整参数 \( \mu \) 和 \( \sigma \),可以生成不同的高斯分布曲线[^1]。
#### 2. 超高斯分布 (Super-Gaussian Distribution)
超高斯分布在某些领域被用于描述具有更尖锐峰值和更快衰减边界的概率分布。其形式通常由指数幂次扩展而来,例如:
\[
g(x|a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z)= e^{-(\frac{|x-c|^n}{d})}
\]
这里我们简化为一种常见的形式来展示超高斯分布的效果[^1]。
---
### Python 实现代码
以下是一个完整的代码示例,展示了如何使用 `matplotlib` 同时绘制高斯分布和超高斯分布的曲线图。
```python
import numpy as np
import matplotlib.pyplot as plt
# 设置字体支持中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 定义高斯分布函数
def gaussian_distribution(x, mu, sigma):
return (1 / (np.sqrt(2 * np.pi) * sigma)) * np.exp(-((x - mu)**2) / (2 * sigma**2))
# 定义超高斯分布函数
def super_gaussian_distribution(x, mu, sigma, n=4): # 默认设置 n=4 来增强尖峰效果
return (1 / (np.sqrt(2 * np.pi) * sigma)) * np.exp(-(((x - mu)**2) / (2 * sigma**2))**(n/2))
# 参数设定
u1 = 0 # 均值
sigma1 = 1 # 标准差
n_value = 4 # 超高斯分布中的形状因子
# 数据范围
x = np.linspace(-5, 5, 1000)
# 计算对应的y值
y_gauss = gaussian_distribution(x, u1, sigma1)
y_super_gauss = super_gaussian_distribution(x, u1, sigma1, n=n_value)
# 创建子图并绘制
fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(x, y_gauss, label='高斯分布', color='blue')
ax.plot(x, y_super_gauss, label=f'超高斯分布(n={n_value})', color='red')
# 添加标题和标签
ax.set_title('高斯分布 vs 超高斯分布')
ax.set_xlabel('X轴')
ax.set_ylabel('Y轴')
ax.legend()
# 显示图形
plt.grid(True)
plt.show()
```
---
### 结果解释
上述代码实现了两个主要功能:
1. 使用 `gaussian_distribution()` 函数计算经典高斯分布的概率密度。
2. 使用 `super_gaussian_distribution()` 函数引入额外的形状因子 \( n \),从而生成更加尖锐的超高斯分布曲线[^1]。
最终的结果会以蓝色表示经典的高斯分布曲线,红色则代表超高斯分布曲线。
---
###
阅读全文
相关推荐













