问题
As the title indicates I would like to make a contour plot by using three 1D arrays. Let's say that
x = np.array([1,2,3])
and
y = np.array([1,2,3])
and
z = np.array([20,21,45])
To do a contourplot in matplotlib i meshed the x
and y
coordinate as X,Y = meshgrid(x,y)
but then the z
array must also be a 2D array. How do I then turn z
into a 2d array so it can be used?
回答1:
Your z
is wrong. It needs to give the values at every point of the mesh. If z
is a function of x
and y
, calculate z
at what I refer to as X_grid
below:
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return (x[:,0]**2 + x[:,1]**2)
x = np.array([1,2,3])
y = np.array([1,2,3])
xx, yy = np.meshgrid(x, y)
X_grid = np.c_[ np.ravel(xx), np.ravel(yy) ]
z = f(X_grid)
z = z.reshape(xx.shape)
plt.contour(xx, yy, z)
回答2:
It seems to me that you're describing a one-dimensional curve through the space rather than a surface. I say that bacause I assume x[i]
, y[i]
and z[i]
are the coordinates of a point. You cannot use these points to define a surface in an easy way, because your points only depend on one variable i
and so only describes a shape with one degree of freedom. Consider that you can connect each point in the list to the next, and that this only gives you a one dimensional chain of points. In oder to make a surface out of three arrays, you must define 9 z values, not 3.
I'm sorry that this isn't a helpful answer, but I don't have the reputation to post a comment.
回答3:
I encounter this issue frequently if I am using data that I had raveled for easier manipulation. In the raveled data a 2-D array is flattened.
The original data has x, y, and z values for every coordinate:
x = [0, 1, 2; 0, 1, 2]
y = [0, 0, 0; 1, 1, 1]
z = [0.1 , 0.2, 0.3 ; 0.2, 0.3, 0.4]
Using np.ravel() for all three arrays makes them a one-dimensional 6 element long array.
xx = np.ravel(x); yy = np.ravel(y) ; zz = np.ravel(z)
Now xx = ([0, 1, 2, 0, 1, 2]), and similarly for yy and zz.
If this is the kind of data you are working with and the data is thoroughly sampled, you can simulate a contourf plot using a scatter plot. This only works if your dataset is sampled well enough to fill in all of the space.
plt.scatter(xx,yy,c=zz,cmap=cm.Reds)
来源:https://stackoverflow.com/questions/41897544/make-a-contour-plot-by-using-three-1d-arrays-in-python