-1

I am trying to draw contour lines (elevation) associated with x and y coordinates. I have read examples here on how you draw contours on Matplotlib when z is defined by x and y but how can I draw contour lines that are independent of x and y?

This is my code:

import numpy as np
import matplotlib.pyplot as plt

data = [(0, 200, 140), (100, 430, 260), (800, 340, 320), (250, 110, 430), (290, 40, 100), (590, 35, 180)]
x = np.arange(0, 900, 20)
y = np.arange(0, 500, 20)
X, Y = np.meshgrid(x, y)
Z = [i[2] for i in data]
Z = np.array(Z)
plt.figure()
plt.contour(X, Y, Z)
plt.show()

I get an error "TypeError: Input z must be a 2D array."

This is the first time I am trying to draw contour lines and I appreciate any help on this.

owl
  • 1,841
  • 6
  • 20
  • 30
  • 1
    If this is your first time, why wouldn't you read the `plt.contour` documentation and have a look at some examples before rolling your own code? – DYZ Feb 05 '18 at 23:53
  • 1
    Of course z must be dependent on x and y. But all that means is that for each x and y you need one z point. Whether or not there is some physical or mathematical relation between the points is rather irrelevant. The problem here is that you only have 6 data points, while you have 1125 x and y points. Hence it's not really clear what you are trying to achieve. – ImportanceOfBeingErnest Feb 05 '18 at 23:55
  • Thank you to both of you for your comments. I did of course read the plt.contour document many times but I could not figure it out how I am supposed to have X, Y, and Z arrays. Also, I posted just a simplified example and the actual data points were 30000+. Sorry for being unclear. – owl Feb 06 '18 at 02:11

1 Answers1

2

Given that there are only 6 data points, a contour plot drawn from those may not be very informative. Still, the concept would be the same for more points.

Of course one cannot draw contour lines where x,y and z are independent. If you have 6 z points, you need 6 x points and 6 y points - which you have. So the solution may be rather trivial - just use tricontour instead of contour:

import numpy as np
import matplotlib.pyplot as plt

data = [(0, 200, 140), (100, 430, 260), (800, 340, 320), 
        (250, 110, 430), (290, 40, 100), (590, 35, 180)]
x,y,z = zip(*data)
plt.figure()
plt.tricontour(x,y,z)
plt.show()

enter image description here

More generally, you may also interpolate your data. See Make contour of scatter.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Thank you so much for answering so quickly! I spent hours looking up and trying to figure out what I am doing wrong. It worked on my original data set as well!! Thank you also for the link for making contour of scatter. I did not find that before I posted my question. – owl Feb 06 '18 at 02:30