使用MatPlotLib根据z值矩阵生成等高线图
假设我有一个字典,里面存的是列表:
dict = {}
for x in range(0, 11):
dict[x] = [0,1,2,3,4,5,6,7,8,9,10]
我该怎么从这些数据中创建一个等高线图呢?这个数据结构基本上是一个z值的矩阵,其中x和y坐标分别对应字典的键和值。
1 个回答
1
如果我理解你的数据类型没错的话,要把它转换成一个numpy数组,然后再画图,你可以这样做:
import numpy as np
import pylab as plt
# The example dict/matrix
dict = {}
for x in range(0, 11):
dict[x] = [0,1,2,3,4,5,6,7,8,9,10]
# Create an empty numpy array with the right dimensions
nparr = np.zeros((len(dict.keys()), len(dict[0])))
# Loop through converting each list into a row of the new array
for ii in xrange(nparr.shape[0]):
nparr[ii] = dict[ii]
# Plotting as a contour
plt.contour(nparr)
plt.show()
需要注意的是,对于非常大的数据集,使用这个for循环可能会比较慢,但对于“图像大小”的数据来说应该没问题(我想无论如何,matplotlib在渲染时会花费最多的时间)。