4

I have some data defined on a regular Cartesian grids. I'd like to show only some of them with a condition based on the radius from the center. This will effectively create a ring-like structure with a hole in the center. As a result, I cannot use imshow. tricontourf or tripcolor are what I found to deal with it. My code looks something like this:

R = np.sqrt(x**2+y**2)
flag = (R<150)*(R>10)
plt.tricontourf(x[flag], y[flag], data[flag], 100)

where x and y are mesh grids where data defines. The problem here is that both tricontourf and tripcolor try to fill the middle of the ring, where I hope can be left blank.

To be more specific, the one in the left is similar to what I want but I can only get the one in the right with this piece of code shown above.

Sample plots

Fxyang
  • 293
  • 3
  • 6
  • 12

2 Answers2

2

The following shows how to mask some parts of the plot based on a condition. Using imshow is perfectly possible, and that's what the script below is doing.

The idea is to set all the unwanted parts of the plots to nan. To make the nan values disappear, we can set their alpha to 0, basically making the plot transparent at those points.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-150, 150, 300)
y = np.linspace(-150, 150, 300)
X,Y = np.meshgrid(x,y)
data = np.exp(-(X/80.)**2-(Y/80.)**2)

R = np.sqrt(X**2+Y**2)
flag =np.logical_not( (R<110) * (R>10) )
data[flag] = np.nan

palette = plt.cm.jet
palette.set_bad(alpha = 0.0)

im = plt.imshow(data)

plt.colorbar(im)
plt.savefig(__file__+".png")
plt.show()

enter image description here


Just to add that also tricontourf can do what you're asking about. This example from the matplotlib gallery shows exactly what you're looking for, while this question on SO deals with a similar issue in a more comprehensive way.
Community
  • 1
  • 1
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
0

Try creating fake data points in the inner hole and set them to np.nan or np.inf. Alternately, you could set them to a high value (in your case, say simply 1) and then pass limits to the colour scale so that these high regions are not plotted.

VBB
  • 1,305
  • 7
  • 17
  • I tried both `np.nan` and `np.inf`. Both of them give me plots where the middle has one color and the rest has the color corresponding to `0`. As of the alternative method, I tried to set `vmax` to limit the color scale. In that case, all bigger values are plotted as having the maximum value. – Fxyang Jan 18 '17 at 16:41
  • If you set `np.nan`, you will have to set the contour levels manually. – VBB Jan 19 '17 at 07:31