سؤال

So I have a data set that is in the matrix form:

x1, Y1, VALUE1
x2, Y1, VALUE2
x3, Y1, VALUE3

x1, Y2, VALUE4
x2, Y2, VALUE5
x3, Y2, VALUE6

and so on. I get my contours properly except my x and y axes go from say 1, 2, 3...N. This is fine because it is representing pixels so isn't incorrect, but I would like to change the axes values from pixels to the actual units. I can't seem to find a way to instruct contour to allow me to add this.

bsquare=np.reshape(value,(x length,y length))
blue=contour(bsquare,colors='b')
plt.show()

where xlength and ylength are the number of points in either axis.

هل كانت مفيدة؟

المحلول

plt.contour can be given arrays X, Y, Z then it takes the Z as the contour values and the X and Y are used on their respective axes. Here is a script that first makes some data to play with, then gets into an array of the form you describe:

import matplotlib.pyplot as plt
import numpy as np

# Make some test data 
nx = 2
ny = 3
x = np.linspace(0, 3, nx)
y = np.linspace(50, 55, ny)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) + Y

# Now get it into the form you describe
data = [[[x[i], y[j], Z[j, i]] for i in range(nx)] for j in range(ny)]
data = np.array(data)
print data

>>> 
[[[  0.          50.          50.        ]
  [  3.          50.          50.14112001]]

 [[  0.          52.5         52.5       ]
  [  3.          52.5         52.64112001]]

 [[  0.          55.          55.        ]
  [  3.          55.          55.14112001]]]

Note I am using a numpy.array not just a normal list this is important in the next step. Lets split up that data as I presume you have done into the x and y values and the values themselves:

# Now extract the data 
x_values = data[:, :, 0]
y_values = data[:, :, 1]
values = data[:, :, 2]

Now all of these things are nx, ny arrays, that is they have the same shape as your bsquare. You can check this by printing values.shape and changing the integers nx, ny. Now I will plot three things:

  1. Firstly as you have done simply contour plot the values, this automatically adds the axes values

  2. Secondly I plot using the arrays to give the correct scalings and

  3. Finally I will plot the origin data set to show it properly recovers the data.

You will need to compare the axis values with where the fake data was created:

fig, axes = plt.subplots(ncols=3, figsize=(10, 2))
axes[0].contour(values)
axes[1].contour(x_values, y_values, values)
axes[2].contour(X, Y, Z)

enter image description here

How you implement this will largely depend on how you have imported your data. If you can simply turn it into a numpy.array() then I think this will solve your issue.

Hopefully I understood your problem correctly.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top