user354134
user354134

Reputation:

Python/MatPlotLib yield odd, unexpected contours

I'm trying to contour plot a function that's 0 at the 4 vertices of the unit square, and 1 in the middle of that square. I tried this:

import matplotlib.pyplot 
z = [[0,0,0], [1,0,0], [0,1,0], [1,1,0], [.5,.5,1]] 
cn = matplotlib.pyplot.contour(z) 
matplotlib.pyplot.show(cn) 

And got this:

enter image description here

I expected a series of concentric squares, like this:

enter image description here

which is what I get when I do

ListContourPlot[{{0,0,0}, {1,0,0}, {0,1,0}, {1,1,0}, {.5,.5,1}}, 
ColorFunction -> (Hue[#1]&)] 

in Mathematica.

What did I do wrong?

EDIT: I realize there's more than one way to draw contours for given data. In this case, a series of concentric circles would also have been fine.

Upvotes: 1

Views: 466

Answers (2)

pelson
pelson

Reputation: 21829

For non-meshed data, as suggested in the comments, you probably want to use the tricontour function:

>>> import matplotlib.pyplot as plt
>>> z = [[0,0,0], [1,0,0], [0,1,0], [1,1,0], [.5,.5,1]] 
>>> x, y, z = zip(*z)
>>> cn = plt.tricontourf(x, y, z)
>>> plt.show()

output

HTH

Upvotes: 4

tacaswell
tacaswell

Reputation: 87366

The problem is because the expected inputs are entirely different

mathematica ContourListPlot expects (the way you are calling it) a list of points of the form {x, y, z}.

In matplotlib contour (the way you are calling it) expects an array of z values.

Given your input, it is generating the correct contours. To see this clearly look at imshow(z).

Upvotes: 4

Related Questions