Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Elegant solution to 'thin out' array and plot line

Sometimes I don't know how many points will be in the target array, yet I need to plot a line with markers. If too many points presented, markers on the plot will overlap and an single bold line will be plotted:

line([(x, np.sin(x)) for x in srange(0,np.pi,np.pi/128)], marker='d')

The solution acceptable for me is to 'thin out' input array in order to exclude points, which are too close to each other. My first implementation of such functional is:

def thin_out_array(points, size):
    if len(points) <= size: return points
    g = int(len(points)/size)
    return [p for i,p in enumerate(points) if i % g == 0]

def line(points, thin_out = None, **kwds):
    if thin_out: points = thin_out_array(points, thin_out)
    return sage.plot.line.line(points, **kwds)

So this code gives line with separated markers:

line([(x, np.sin(x)) for x in srange(0,np.pi,np.pi/128)], marker='d', thin_out = 32)

Perhaps, more clear and common way to do such thing is already designed?