contour plot代码
时间: 2024-09-28 11:16:48 浏览: 46
Contour plots, also known as level plots or isolines, are a graphical representation used in mathematics and scientific data analysis to show the variation of a function or dataset across multiple dimensions. In Python, you can create contour plots using the `matplotlib` library, which is often combined with `numpy` for numerical computations.
下面是一个简单的例子,展示如何使用`matplotlib.pyplot`模块创建一个二维函数的contour plot:
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义数据区域
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
# 创建一个示例函数
Z = X**2 + Y**2
# 创建并显示contour plot
fig, ax = plt.subplots()
cs = ax.contour(X, Y, Z, levels=range(0, 100, 20)) # 绘制等高线
ax.clabel(cs) # 添加标签
plt.title('Contour Plot Example')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show() # 显示图形
```
在这个例子中,我们首先生成了网格点 `(X,Y)`,然后计算了一个简单的函数值 `Z`。接着,`contour()` 函数用于绘制等高线,`clabel()` 添加了等高线的标签。最后,通过 `plt.show()` 展示了结果。
阅读全文