public
Created

Quick matplotlib script to create pictures for array visualizations.

  • Download Gist
array-viz.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
import pylab
import pandas as P
import numpy as np
 
def draw_array(a, target=None):
fig = pylab.gcf()
fig.frameon = False
ax = fig.gca()
#ax.set_axis_off()
ax.patch.set_facecolor('white')
ax.set_aspect('equal', 'box')
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
size = 1.0
z_scale = 1.4
i = 0
for z in reversed(range(a.shape[2])):
for (x,y),v in np.ndenumerate(a[:, :, z]):
i += 2
alpha = a['transparency'][x,y,z]
color = tuple(a['color'][x,y,z])
off_x = 0.01 + x + size + z / z_scale
off_y = y + size + z / z_scale
rect = pylab.Rectangle([off_x, off_y], size, size,
facecolor=color, edgecolor=(0,0,0),
zorder = i, alpha = alpha)
ax.add_patch(rect)
cx = off_x + size/2
cy = off_y + size/2
# sigh
label = str(a['name'][x,y,z])
w, h = pylab.matplotlib.text.TextPath((0,0), label).get_extents().size / 30
#print w, h
text = pylab.Text(cx - w / 2, cy - h / 2, label, zorder=i+1)
ax.add_artist(text)
ax.autoscale_view()
if target is not None:
pylab.savefig(target)
return ax
 
class draw_slice(object):
def __init__(self, a, target=None):
self.a = a
self.target = target
def __getitem__(self, slc):
slice_z = np.copy(self.a)
slice_z['color'][slc] = (0.9, 0.5, 0.3)
slice_z['transparency'] = 0.9
draw_array(slice_z, self.target)
 
default_size = (3, 3, 5)
np.random.seed(1)
names = np.random.randint(0, 5, np.prod(size)).reshape(size)
 
def make_array(shape=default_size):
a = np.ndarray(shape, dtype=([('color', 'f,f,f'),
('name', 'i'),
('transparency', 'f')]))
a['transparency'] = 1.0
a['color'] = (1,1,1)
return a
 
default = make_array()
default['name'] = names
ax = draw_array(default, target='array.pdf')
 
 
mapped = np.copy(default)
mapped['name'] += 100
draw_array(mapped, 'array+100.pdf')
 
draw_slice(default, 'slice-x.pdf')[1,:,:]
draw_slice(default, 'slice-y.pdf')[:,1,:]
draw_slice(default, 'slice-z.pdf')[:,:,1]
draw_slice(default, 'slice-box.pdf')[1:3,1:3,1:3]
 
mapped = default.copy()
mapped['name'][1:3,1:3,1:3] += 100
draw_slice(mapped, 'slice-add.pdf')[1:3,1:3,1:3]
 
 
draw_slice(default, 'filter-small.pdf')[default['name'] <= 1]
 
mapped = np.copy(default)
filter = mapped['name'] <= 1
mapped['name'][filter] += 100
draw_slice(mapped, 'filter-add.pdf')[filter]
 
reduced = make_array(shape=(3,3,1))
reduced['name'][:,:,0] = np.sum(default['name'], axis=2)
draw_array(reduced, 'reduced.pdf')

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.