From: Eric Firing [mailto:efiring@…202…]

Sent: Wednesday, June 06, 2012 13:41

To: matplotlib-users@lists.sourceforge.net

Subject: Re: [Matplotlib-users] scatter plot with constant x

>> ...

>> No, but you can do this:

>>

>> plt.plot([3] * 4, [60, 80, 120, 180], ...)

>

> This started from a simple enough question, but it got me

thinking about what the fastest way to do this is (in case

you have HUGE arrays, or many loops over them).

[...]

Since we end up needing float64 anyway:

In [3]: %timeit l=np.empty(10000,dtype=np.float64); l.fill(3)

100000 loops, best of 3: 14.1 us per loop

In [4]: %timeit l=np.zeros(10000,dtype=np.float64);l[:]=3

10000 loops, best of 3: 26.6 us per loop

Eric

Numpy's as_strided came to mind; it can make a large array that's really a

view of a one-element array:

In [1]: as_strided = np.lib.stride_tricks.as_strided

In [2]: s = as_strided(np.array([3], dtype=np.float64), shape=(10000,),

...: strides=(0,))

In [3]: s[0] = 4

In [4]: s[9999] # all elements share data

Out[4]: 4.0

It's somewhat slower to create the base array and the view than to create and

fill a 10000-element array:

In [5]: %timeit l = np.empty(10000, dtype=np.float64); l.fill(3)

100000 loops, best of 3: 10.1 us per loop

In [6]: %timeit s = as_strided(np.array([3], dtype=np.float64),

shape=(10000,), strides=(0,)) # line broken for email

10000 loops, best of 3: 21.6 us per loop

However, once created, its contents may be changed much more quickly:

In [7]: l = np.empty(10000, dtype=np.float64)

In [8]: %timeit l.fill(3)

100000 loops, best of 3: 7.71 us per loop

In [9]: %timeit s[0] = 3

10000000 loops, best of 3: 116 ns per loop

Numpy's broadcast_arrays uses as_strided under the hood. Code could look

like:

x, y = np.broadcast_arrays(3, [60, 80, 120, 180])

plt.plot(x, y, '+')

x[0] = 21 # new x for all samples

plt.plot(x, y, 'x')

## ···

On 06/06/2012 06:42 AM, Ethan Gutmann wrote: