4
$\begingroup$
data = {5.0, 2.9, 9.9, 14.5, 6.8, 4.2};
mean = {2.2, 3.4, 8.1, 13.6, 7.5, 3.5};

ListPlot[{data, mean}, Filling -> {1 -> {2}}, 
 PlotLegends -> {"data", "mean"}, PlotTheme -> "Detailed"]

enter image description here

I would like to color the points above mean green and below mean red. The only solution I found is to use Graphics:

color = If[# > 0, Darker @ Green, Red] & /@ (data - mean);

Graphics[
 {
  PointSize@Large,
  Blue,
  Point @ Transpose[{Range@Length@mean, mean}],
  Transpose[{color, Point /@ Transpose[{Range@Length@data, data}]}]
  },
 AspectRatio -> 1/GoldenRatio,
 Frame -> True,
 GridLines -> Automatic,
 GridLinesStyle -> Directive[Gray, Dashed]]

enter image description here

Is there a way to obtain a similar result with ListPlot?

$\endgroup$
  • $\begingroup$ This looks like a good application of DataListPlot. If I get the time, I'll write it up. $\endgroup$ – rcollyer Nov 18 '15 at 17:32
7
$\begingroup$

It think this might work for you:

ListPlot[
  {
   MapThread[Style[#1, If[#1 - #2 >= 0, Darker@Green, Red]] &, {data, mean}],
   mean
  },
  PlotLegends -> {"data", "mean"}, PlotRange -> {{0, 7}, Automatic},
  PlotStyle -> PointSize[0.02], PlotTheme -> "Detailed"
]

Mathematica graphics

$\endgroup$
  • 1
    $\begingroup$ Astonishing! +1 $\endgroup$ – eldo Nov 18 '15 at 17:46
  • $\begingroup$ never would have thought to try that, ! Is this a new feature? $\endgroup$ – george2079 Nov 18 '15 at 17:54
  • $\begingroup$ @george2079 It may be, or at least I noticed this usage in the documentation for ListPlot for the first time in v. 10.3. Compare e.g. the current docs with the 10.2 version of the same page. $\endgroup$ – MarcoB Nov 18 '15 at 18:08
  • 2
    $\begingroup$ I would use PlotMarkers to better differentiate between the two data sets, but ListPlot uses Inset for PlotMarkers which means Style is not correctly applied. This is fixed by adding Method -> {"OptimizePlotMarkers" -> False} to the options. +1 for being simple. $\endgroup$ – rcollyer Nov 18 '15 at 18:23
  • $\begingroup$ nice. It works in 10.1 (undocumented). The trick works with Plot too, Plot[Style[x^2, Dashed], {x, -1, 1}] $\endgroup$ – george2079 Nov 18 '15 at 18:47
2
$\begingroup$

This an addendum to MarcoB's answer. I think for this plot it would be better to exert more control over PlotLegends. I suggest generating the legend like so:

With[{loColr = Red, hiColr = Darker@Green, mnColr = Orange},
  ListPlot[{
    MapThread[
      Style[#1, If[#1 - #2 >= 0, hiColr, loColr]] &, {data, mean}],
    mean},
    PlotLegends ->
      PointLegend[{hiColr, loColr, mnColr}, {"above mean", "below mean", "mean"}],
    PlotRange -> {{0, 7}, Automatic},
    PlotStyle -> PointSize[0.02],
    PlotTheme -> "Detailed"]]

plot

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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