1

I have an array

  d[0:100]

which is defined in boxes (or cells) whose center are stored in these two arrays

  x[0:100]
  y[0:100]

and whose size is

  h[0:100]

I wish I could plot an image showing boxes/cells colored according to the value of the array defined in each of them. It seems and histogram but it is not. Do you have any idea where to start?

wim
  • 338,267
  • 99
  • 616
  • 750
Brian
  • 13,996
  • 19
  • 70
  • 94
  • i would use `matplotlib` for sure, but the question is not very clear.. so you want to plot a bunch of coloured squares, whose centers are at (x,y), edge lengths are h, and what's the colour? is it an rgb tuple in d? – wim Aug 01 '11 at 10:36
  • Try looking into [PIL](http://www.pythonware.com/products/pil/) (Python Photo Imaging Library) – jcfollower Aug 01 '11 at 12:19

1 Answers1

2

Given the desire to draw squares with area h**2 and a color based on the value in d, you could draw rectangles using matplotlib with a color obtained from a colormap (scaled to 0-1):

import pylab
import numpy as np
import matplotlib as mpl
import random
import matplotlib.cm as cm

my_cmap = cm.bone

def my_square_scatter(axes, x_array, y_array, size_array, color_array):
    for x, y, size, color in zip(x_array, y_array, size_array, color_array):
        square = pylab.Rectangle((x-size/2,y-size/2), size, size, facecolor = my_cmap(color))
        axes.add_patch(square)
    return True

x = np.arange(100)
y = np.arange(100)
random.shuffle(y)
h = np.arange(100)/10.0
d = np.arange(100)/100.0
random.shuffle(d)

fig = pylab.figure(1)
fig.clf()
axes = pylab.axes()
my_square_scatter(axes, x, y, h, d)
pylab.axis('scaled')

#Create your own colorbar based on the parent axes.
ax, _ = mpl.colorbar.make_axes(axes)
cbar = mpl.colorbar.ColorbarBase(ax, cmap=my_cmap, norm=mpl.colors.Normalize(vmin=0.0, vmax=1.0))
#cbar.set_clim(0.0,1.0) #Scale the colorbar; default is 0--1


pylab.show()

Sample output:

my_square_scatter output

Your d array should be normalized to 0-1. Otherwise you should scale this in the color selection.

Adapted from Plot/scatter position and marker size in the same coordinates.

Community
  • 1
  • 1
Daan
  • 2,049
  • 14
  • 21
  • Thank, but one more question. I need to have a legend of the color of the boxes. I tried with pylab.colorbar() but it didn't work. Sorry I'm not that good at python. – Brian Aug 01 '11 at 15:01
  • I've added code for a custom colorbar. You can make a colorbar based on the parent axes and set the ranges yourself. Normally this is based on the range of your data in your plot if you use imshow/contour/pcolor/&c., but now you have to tell the colorbar yourself what the min/max values are. Code from: http://stackoverflow.com/questions/3373256/set-colorbar-range-in-matplotlib – Daan Aug 02 '11 at 07:31