I need to create images from some image data in the form of a (d x d) list of integer values representing the color of the corresponding pixel.

For small dimension images, I can use Grid:

d = 30;
g = RandomInteger[3, {d, d}]; (* Simulated data *)
dots = Table[Reap[Do[Do[If[g[[i, j]] == t, Sow[{i, j}]], {j, 1, d}], {i, 1, 
  d}]][[2, 1]], {t, 0, 3}];
color = {White, Gray, Green, Red};
Grid[Table[  , d, d], Background -> {None, None, Flatten[Table[Table[dots[[j, i]] -> color[[j]], {i, 1, Length[dots[[j]]]}], {j, 1, 4}]]}]

For larger dimensions (2000 x 2000), the Grid image is far too large to display, so I use ListPlot with Large/Medium/Small points, but that creates gaps or overlaps between the points:

ListPlot[dots, PlotStyle -> PointSize[Small], AspectRatio -> 1]

Is there a way I can solidly color a fine grid?

My clunky conversion of g into dots in the 3rd line is only necessary for putting the data into a form Grid or ListPlot can handle. My data will be in a form like g so if we can skip the Reap/Sow step that'd be more efficient.


3 Answers 3



gg = RandomInteger[3, {d, d}];

ArrayPlot[gg, ColorRules -> Thread[Range[0, 3] -> color]]
(* or *) ArrayPlot[gg /. Thread[Range[0, 3] -> color]]

Mathematica graphics


How about this:

Create a matrix with the color in each cell:

im = Map[Piecewise[{{White, # == 0}, {Gray, # == 1}, {Green, # == 
       2}, {Red, # == 3}}] &, g, {2}];

Show the matrix as an image:


enter image description here

data = RandomInteger[3, {d, d}];

Graphics[Raster[data, ColorFunction -> (color[[# + 1]] &)]]

And of course if you want an image you can Rasterize the Graphics


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.