Differences between revisions 1 and 2

Deletions are marked like this. Additions are marked like this.
Line 5: Line 5:
import matplotlib.numerix.ma as M
from pylab import *

from matplotlib.font_manager import fontManager, FontProperties
import numpy as np
import matplotlib.pyplot as plt
Line 18: Line 15:
y_values = M.array(y_values) y_values = np.ma.array(y_values)
Line 20: Line 17:
y_values_masked = M.masked_where(y_values < threshold , y_values) y_values_masked = np.ma.masked_where(y_values < threshold , y_values)
Line 23: Line 20:
plot(x_values, y_values,'ko')
title('All values')
plot(x_values, y_values_masked,'ko')
title('Plot without masked values')
a = subplot(313)
.plot(x_values, y_values_masked,'ko')
plot(x_values, y_values,'ko')
plt.title('All values')
plt.plot(x_values, y_values_masked,'ko')
plt.title('Plot without masked values')
ax = plt.subplot(313)
.plot(x_values, y_values_masked,'ko')
Line 33: Line 30:
a.set_xlim(x_values[0], x_values[-1]) 
title('Plot without masked values -\nwith full range x-axis')
ax.set_xlim(x_values[0], x_values[-1])
plt.title('Plot without masked values -\nwith full range x-axis')

From time to time one might end up with "meaningless" data in an array. Be it because a detector didn't work properly or for an other reason. Or one has to deal with data in completely different ranges. In both cases plotting all values will screw up the plot. This brief example script addresses this problem and show one possible solution using masked arrays. See 'masked_demo.py' in the matplotlib examples for a reference, too.

   1 import numpy as np
   2 import matplotlib.pyplot as plt
   4 y_values = [0,0,100,97,98,0,99,101,0,102,99,105,101]
   5 x_values = [0,1,2,3,4,5,6,7,8,9,10,11,12]
   7 #give a threshold
   8 threshold = 1
  10 #prepare for masking arrays - 'conventional' arrays won't do it
  11 y_values = np.ma.array(y_values)
  12 #mask values below a certain threshold
  13 y_values_masked = np.ma.masked_where(y_values < threshold , y_values)
  15 #plot all data
  16 plt.subplots_adjust(hspace=0.5)
  17 plt.subplot(311)
  18 plt.plot(x_values, y_values,'ko')
  19 plt.title('All values')
  20 plt.subplot(312)
  21 plt.plot(x_values, y_values_masked,'ko')
  22 plt.title('Plot without masked values')
  23 ax = plt.subplot(313)
  24 ax.plot(x_values, y_values_masked,'ko')
  25 #for otherwise the range of x_values gets truncated:
  26 ax.set_xlim(x_values[0], x_values[-1])
  27 plt.title('Plot without masked values -\nwith full range x-axis')
  29 savefig('masked_test.png')

The resulting figure might illustrate the problem - note the different scales in all three subplots:


Cookbook/Matplotlib/Plotting values with masked arrays (last edited 2011-02-01 03:43:54 by UnuTbu)