|
From: Drain, T. R (392P) <the...@jp...> - 2013-08-02 18:53:22
|
Thanks! Either of those looks like it will work. I'll play w/ both of them to see which fits better w/ my existing code. Ted ________________________________ From: Goodman, Alexander (398J-Affiliate) [go...@jp...] Sent: Friday, August 02, 2013 11:16 AM To: Benjamin Root Cc: Drain, Theodore R (392P); mat...@li... Subject: Re: [Matplotlib-users] Splitting arrays into chunks that satisfy a condition? Hi Ted, As far as actually splitting up a numpy array into contiguous chunks fulfilling a condition, there is a very good solution posted on stackoverflow: http://stackoverflow.com/questions/4494404/find-large-number-of-consecutive-values-fulfilling-condition-in-a-numpy-array If you use the contiguous_regions function from the first answer, this code should give you what you want: xneg = [x[slice(*reg)] for reg in contiguous_regions(z < 0)] xpos = [x[slice(*reg)] for reg in contiguous_regions(z >= 0)] Thanks, Alex On Fri, Aug 2, 2013 at 10:45 AM, Benjamin Root <ben...@ou...<mailto:ben...@ou...>> wrote: On Fri, Aug 2, 2013 at 1:36 PM, Drain, Theodore R (392P) <the...@jp...<mailto:the...@jp...>> wrote: I have three arrays (x,y,z). I want plot x vs y and draw the line segments differently depending on whether or not z is positive or negative. So I'm trying to split the x,y arrays into chunks depending on the value of z. Using numpy.where, I can find the indeces in z that satisfy a condition but I can't figure out an efficient way (other than brute force) to split the array up into continuous chunks. Does anyone know of a numpy trick that would help with this? Here's a simple example: # index: 0 1 2 3 4 5 6 7 8 9 z=numpy.array([-1,-1,-1, 1, -1,-1,-1, 1,1,1] ) x=numpy.array([-2,-3,-4, 2, -5,-6,-7, 3,4,5] ) # Want: xneg = [ x[0:3], x[4:7] ], xpos = [ x[3:4], x[7:10] ] xneg = [ [-2,-3,-4], [-5,-6,-7] ] xpos = [ [ 2 ], [ 3, 4, 5 ] ] idxneg = numpy.where( z < 0 )[0] # == [ 0,1,2, 4,5,6 ] idxpos = numpy.where( z >= 0 )[0] # == [ 3, 7,8,9 ] Thanks, Ted One way I would go about it is to do this: z1 = numpy.where(z < 0, z, numpy.nan) z2 = numpy.where(z >= 0, z, numpy.nan) And then plot those against x. matplotlib ignores nans and would break up the line where-ever a nan shows up (assuming that is the effect you want). Cheers! Ben Root -- Alex Goodman |