3

I'm attempting to mask a data array, whereby for every value in the array less than 9 I wish to set this to 0. Every value greater than 9 I wish to set to 1. Such that when I multiply this array by the array I wish to mask, any value will either be multiplied by 0 (thus masking that data) or (1) i..e, that data will remain. Hopefully, that makes sense...!

I was wondering how matplotlib would plot two arrays of equal dimensions together, say if one element in the array was "nan" and the other corresponding element was say, 42. Would matplotlib automatically not plot this value?

I assume it would but I would just like some verification on this point. Many thanks.

2 Answers 2

1

If you mask the arrays, you can plot them normally. If you add two masked arrays, the masks are combined properly as you can see in the example below. I have generated random data between 0 and 20 and mask all the values less than 9 in both arrays.

import numpy as np
import matplotlib.pyplot as pl

# Create random data between 0 and 20.
a = np.random.rand(10, 10)*20
b = np.random.rand(10, 10)*20

# Mask all values less than 9.
a = np.ma.array(a, mask=a < 9.)
b = np.ma.array(b, mask=b < 9.)

# Plot a, b and the sum of both.
pl.subplot(131)
pl.pcolormesh(a, cmap=pl.cm.hot)
pl.subplot(132)
pl.pcolormesh(b, cmap=pl.cm.hot)
pl.subplot(133)
pl.pcolormesh(a+b, cmap=pl.cm.hot)
pl.show()
Sign up to request clarification or add additional context in comments.

3 Comments

If I wanted to create the mask from two arrays, i.e., if a value is less than 9 in one array OR in another array...how could that be done?
Well what I mean is the mask will be if it is less than 9 in either, so need some sort of logic...?
But that is what my example is showing right? The sum a+b leaves out all files that have a mask in a, in b, or in both. Masking works as an OR logical operator.
1

You can build the mask matrix so simple:

numpy.array((yourarray > 9), dtype=int)

You can change the > to >= if you want. The relation you wrote was not clear, you did not define what to do if the values equals to 9.

In case of None, NaN, inf values matplotlib will not plot the point. Eg.

a = numpy.array([1,2,float('nan'),4])
b = numpy.array([40,41,42,43])
pl.plot(a,b,"o")
pl.show()

The third point will not be plotted.

1 Comment

Thank you. Yes a mask has been applied to which if the value is less than 9 I apply a value of nan as I will end up multiplying another array by the mask to ensure it is carried over.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.