matplotlib 2D plot from x,y,z values

不想你离开。 提交于 2019-11-29 15:32:38
Abhijay Ghildyal

Here is one way of doing it:

import matplotlib.pyplot as plt
import nupmy as np
from matplotlib.colors import LogNorm

x_list = np.array([-1,2,10,3])
y_list = np.array([3,-3,4,7])
z_list = np.array([5,1,2.5,4.5])

N = int(len(z_list)**.5)
z = z_list.reshape(N, N)
plt.imshow(z, extent=(np.amin(x_list), np.amax(x_list), np.amin(y_list), np.amax(y_list)), norm=LogNorm(), aspect = 'auto')
plt.colorbar()
plt.show()

I followed this link: How to plot a density map in python?

The problem is that imshow(z_list, ...) will expect z_list to be an (n,m) type array, basically a grid of values. To use the imshow function, you need to have Z values for each grid point, which you can accomplish by collecting more data or interpolating.

Here is an example, using your data with linear interpolation:

from scipy.interpolate import interp2d

# f will be a function with two arguments (x and y coordinates),
# but those can be array_like structures too, in which case the
# result will be a matrix representing the values in the grid 
# specified by those arguments
f = interp2d(x_list,y_list,z_list,kind="linear")

x_coords = np.arange(min(x_list),max(x_list)+1)
y_coords = np.arange(min(y_list),max(y_list)+1)
Z = f(x_coords,y_coords)

fig = plt.imshow(Z,
           extent=[min(x_list),max(x_list),min(y_list),max(y_list)],
           origin="lower")

# Show the positions of the sample points, just to have some reference
fig.axes.set_autoscale_on(False)
plt.scatter(x_list,y_list,400,facecolors='none')

You can see that it displays the correct values at your sample points (specified by x_list and y_list, shown by the semicircles), but it has much bigger variation at other places, due to the nature of the interpolation and the small number of sample points.

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