Polar contour plot in Matplotlib

I have a dataset that I want to use to create a contour plot in polar coordinates using Matplotlib.

My data is as follows:

  • theta - 1D array of angle values
  • radius - 1D array of radius values
  • value - 1D array of values โ€‹โ€‹that I want to use for paths

These are all 1D arrays that align correctly - for example:

 theta radius value 30 1 2.9 30 2 5.3 35 5 9.2 

That is, all values โ€‹โ€‹are repeated many times, so each row of this "table" of three variables defines one point.

How can I create a polar contour plot from these values? I thought about converting the radius and theta values โ€‹โ€‹to x and y values โ€‹โ€‹and did it in Cartesian coordinates, but the contour function requires two-dimensional arrays, and I can't understand why.

Any ideas?

+8
python matplotlib graphing
source share
2 answers

The Matplotlib contour() function expects the data to be ordered as a 2D grid of points and a corresponding grid of values โ€‹โ€‹for each of these grid points. If your data is naturally arranged in a grid, you can convert r, theta to x, y and use contour(r*np.cos(theta), r*np.sin(theta), values) to create your graph.

If your data is not grid related, you should follow Stephen's advice and use griddata() to interpolate your data on the grid.

The following script shows examples of both.

 import pylab as plt from matplotlib.mlab import griddata import numpy as np # data on a grid r = np.linspace(0, 1, 100) t = np.linspace(0, 2*np.pi, 100) r, t = np.meshgrid(r, t) z = (t-np.pi)**2 + 10*(r-0.5)**2 plt.subplot(121) plt.contour(r*np.cos(t), r*np.sin(t), z) # ungrid data, then re-grid it r = r.flatten() t = t.flatten() x = r*np.cos(t) y = r*np.sin(t) z = z.flatten() xgrid = np.linspace(x.min(), x.max(), 100) ygrid = np.linspace(y.min(), y.max(), 100) xgrid, ygrid = np.meshgrid(xgrid, ygrid) zgrid = griddata(x,y,z, xgrid, ygrid) plt.subplot(122) plt.contour(xgrid, ygrid, zgrid) plt.show() 

enter image description here

+8
source share

I donโ€™t know if it is possible to make a direct plot plot, but if you go to Cartesian coordinates, you can use griddata to convert your 1D arrays to 2D.

+3
source share

All Articles