12

Possible Duplicate:
ListPlot with each point a different color and a legend bar

I want to color the points in a list plot using a function of the (x,y) values.

I tried this (example with random data):

ListPlot[RandomReal[1, {100, 2}],
 PlotStyle -> Thick,
 Joined -> False,
 ColorFunction -> Function[{x, y}, Hue[(x + y)/2]]
 ]

Mathematica graphics

But, apparently, ColorFunction requires the data to be joined.

ListPlot[RandomReal[1, {100, 2}],
 PlotStyle -> Thick,
 Joined -> True,
 ColorFunction -> Function[{x, y}, Hue[(x + y)/2]]
 ]

Mathematica graphics

That's a big ugly mess that I don't want. How can I get the points colored without joining them, am I missing something simple here?

s0rce
  • 9,632
  • 4
  • 45
  • 78

4 Answers4

16

One way is to use Joined -> True and replace Line with Point afterwards:

ListPlot[RandomReal[1, {100, 2}], PlotStyle -> Thick, Joined -> True, 
  ColorFunction -> Function[{x, y}, Hue[(x + y)/2]]] /. Line[a__] :> Point[a]

Mathematica graphics

Heike
  • 35,858
  • 3
  • 108
  • 157
15

I propose using Graphics primitives:

data = RandomReal[1, {1000, 2}];

Graphics[{Thick, Point[data, VertexColors -> (Hue /@ Mean /@ data)]},
 AspectRatio -> 1/GoldenRatio,
 Axes -> True
]

Mathematica graphics


Here's another method that does not perform as well, but I like the style:

ListPlot[List /@ data, BaseStyle -> Thick, PlotStyle -> (Hue /@ Mean /@ data)]

Mathematica graphics

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • Do you not think this is a duplicate of the question linked above? The answers are exactly the same by the same users... – rm -rf May 05 '12 at 17:58
  • @R.M hm... I guess I saw that question as being focused on the harder problem of the legend bar. This one is much simpler. I'll be in Chat. – Mr.Wizard May 05 '12 at 17:59
10

Questions on here tend to be asked and answered by morning in my timezone but

Mr Wizard: "I noticed that all of the points in your image are actually small squares. Why is that?"

Some sort of visual artifact when point sizes are small. To modify you could just include a point size in the rule replacement:

ListLinePlot[RandomReal[1, {1000, 2}], 
  ColorFunction -> Function[{x, y}, Hue[(x + y)/2]]] /. 
 Line[a__] :> {AbsolutePointSize[8], Point[a]}

enter image description here

Mike Honeychurch
  • 37,541
  • 3
  • 85
  • 158
7

Here's another route:

ListPlot[RandomReal[1, {100, 2}], PlotStyle -> Thick] /. Point[{v1_, v2__}] :>
   Map[{Apply[Function[{x, y}, Hue[(x + y)/2]], #], Point[#]} &, {v1, v2}]

colorful points

Prompted by Mr. Wizard's fine answer, here is yet another method:

ListPlot[RandomReal[1, {100, 2}], PlotStyle -> Thick] /. Point[pts_] :> 
  Point[pts, VertexColors -> Function[{x, y}, Hue[(x + y)/2]] @@@ pts]
J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574