Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not plotting 'zero' in matplotlib or change zero to None [Python]

I have the code below and I would like to convert all zero's in the data to None's (as I do not want to plot the data here in matplotlib). However, the code is notworking and 0. is still being printed

sd_rel_track_sum=np.sum(sd_rel_track, axis=1)
for i in sd_rel_track_sum:
   print i
   if i==0:
       i=None

return sd_rel_track_sum

Can anyone think of a solution to this. Or just an answer for how I can transfer all 0 to None. Or just not plot the zero values in Matplotlib.

like image 929
Ashleigh Clayton Avatar asked Sep 09 '13 11:09

Ashleigh Clayton


People also ask

How do I avoid scientific notation in MatPlotLib?

If you want to disable both the offset and scientific notaion, you'd use ax. ticklabel_format(useOffset=False, style='plain') .

What does o mean in MatPlotLib?

Here, "o-" has the format fmt = '[marker][line]' and produces a dot as marker and a solid line to connect points. Note that the format string might be confusing to use, so instead all options can be set via usual keyword arguments, plot(y, fmt='[color][marker][line]')


2 Answers

Why not use numpy for this?

>>> values = np.array([3, 5, 0, 3, 5, 1, 4, 0, 9], dtype=np.double)
>>> values[ values==0 ] = np.nan
>>> values
array([  3.,   5.,  nan,   3.,   5.,   1.,   4.,  nan,   9.])

It should be noted that values cannot be an integer type array.

like image 174
Daniel Avatar answered Oct 23 '22 15:10

Daniel


Using numpy is of course the better choice, unless you have any good reasons not to use it ;) For that, see Daniel's answer.

If you want to have a bare Python solution, you might do something like this:

values = [3, 5, 0, 3, 5, 1, 4, 0, 9]

def zero_to_nan(values):
    """Replace every 0 with 'nan' and return a copy."""
    return [float('nan') if x==0 else x for x in values]

print(zero_to_nan(values))

gives you:

[3, 5, nan, 3, 5, 1, 4, nan, 9]

Matplotlib won't plot nan (not a number) values.

like image 21
tamasgal Avatar answered Oct 23 '22 17:10

tamasgal