2D Density Plot with X Y Z data

淺唱寂寞╮ 提交于 2020-05-17 07:26:25

问题


I am trying to plot 2d terrain map with x,y and z (elevation). I followed the steps from the following link but I am getting very weird plot.

Python : 2d contour plot from 3 lists : x, y and rho?

I spent almost half day searching but got nowhere.

import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate

# import data:
import xlrd
loc = "~/Desktop/Book4.xlsx"
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sample=500

# Generate array:
x=np.array(sheet.col_values(0))[0:sample]
y=np.array(sheet.col_values(1))[0:sample]
z=np.hamming(sample)[0:sample][:,None]

# Set up a regular grid of interpolation points

xi, yi = np.meshgrid(x, y)

# Interpolate
rbf = scipy.interpolate.Rbf(x, y, z, function='cubic')
zi = rbf(xi, yi)
# Plot
plt.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower',
           extent=[x.min(), x.max(), y.min(), y.max()])
plt.colorbar()
plt.show()

The first of the following fig is what I am getting and the last one is how it should look like.

Any help shall be appreciated

Link to data file


回答1:


I think the problem is that the data you're giving it is not smooth enough to interpolate with the default parameters. Here's one approach, using mgrid instead of meshgrid:

import numpy as np
import pandas as pd
from scipy.interpolate import Rbf

# fname is your data, but as a CSV file.
data = pd.read_csv(fname).values
x, y = data.T

x_min, x_max = np.amin(x), np.amax(x)
y_min, y_max = np.amin(y), np.amax(y)

# Make a grid with spacing 0.002.
grid_x, grid_y = np.mgrid[x_min:x_max:0.002, y_min:y_max:0.002]

# Make up a Z.
z = np.hamming(x.size)

# Make an n-dimensional interpolator.
rbfi = Rbf(x, y, z, smooth=2)

# Predict on the regular grid.
di = rbfi(grid_x, grid_y)

Then you can look at the result:

import matplotlib.pyplot as plt

plt.imshow(di)

I get:

I wrote a Jupyter Notebook on this topic recently, check it out for a few other interpolation methods, like kriging and spline fitting.



来源:https://stackoverflow.com/questions/58193409/2d-density-plot-with-x-y-z-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!