美文网首页
matplotlib_contours

matplotlib_contours

作者: Ledestin | 来源:发表于2017-05-18 11:01 被阅读17次

本文介绍用matplotlib生成等高线图


Demo.py

import matplotlib.pyplot as plt
import numpy as np
#数据集即三维点 (x,y) 和对应的高度值,共有256个点。
#高度值使用一个 height function f(x,y) 生成。 
#x, y 分别是在区间 [-3,3] 中均匀分布的256个值,
#并用meshgrid在二维平面中将每一个x和每一个y分别对应起来,编织成栅格:
# 定义等高线高度函数
def f(x, y):
    return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(- x ** 2 - y ** 2)

# 数据数目
n = 256
# 定义x, y
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)

# 生成网格数据
X, Y = np.meshgrid(x, y)

#接下来进行颜色填充。使用函数plt.contourf把颜色加进去,位置参数分别为:X, Y, f(X,Y)。
#透明度0.75,并将 f(X,Y) 的值对应到color map的暖色组中寻找对应颜色
# 填充等高线的颜色, 8是等高线分为几部分
plt.contourf(X, Y, f(X, Y), 8, alpha = 0.75, cmap = plt.cm.hot)
# 绘制等高线
#接下来进行等高线绘制。使用plt.contour函数划线。位置参数为:X, Y, f(X,Y)。
#颜色选黑色,线条宽度选0.5。
#现在的结果如图所示,只有颜色和线条,还没有数值Label
C = plt.contour(X, Y, f(X, Y), 8, colors = 'black', linewidth = 0.5)
# 绘制等高线数据
#最后加入Label,inline控制是否将Label画在线里面,字体大小为10。
plt.clabel(C, inline = True, fontsize = 10)

# 将坐标轴隐藏
plt.xticks(())
plt.yticks(())
plt.show()

结果:

Paste_Image.png Paste_Image.png

相关文章

网友评论

      本文标题:matplotlib_contours

      本文链接:https://www.haomeiwen.com/subject/seqsxxtx.html