# Use ColorFunction in ListLinePlot with If

The following code

ListLinePlot[{2, 4, 6, 8, 10, 12},
ColorFunction -> Function[{x, y}, If[x <= 3, Blue, Red]]]


should produce blue lines for $x\le3$ and red lines for $x\ge3$. But instead, the plot contains only blue lines.

Where are my red lines?

• ColorFunctionScaling Jun 18 '12 at 18:05
• Why should I use ColorFunctionScaling? My specific color function delivers Blue or Red – two well defined color directives. Jun 18 '12 at 18:08
• @Deniz B/c ColorFunctionScaling prevents the scaling of the argument, not of the function Jun 18 '12 at 18:50

Try

ListLinePlot[{2, 4, 6, 8, 10, 12},
ColorFunction -> Function[{x, y}, If[x <= 3, Blue, Red]],
ColorFunctionScaling -> False, PlotStyle -> Thick, Mesh -> All,
MeshStyle -> {Orange, PointSize[0.03]}, PlotRange -> 13,
Frame -> True] • Mesh is a substitute for PlotMarkers? Didn't know that! Jun 18 '12 at 20:25
• How to make this color change according to the given values on the same line? For example, smaller values light color and greater values darker colors?
– Naps
Oct 21 at 14:06
• @Naps You can just use dark and light version of a single color. Change the ColorFunction in above code with a function like this Function[{x, y}, If[x <= 3, Lighter@Blue, Darker@Blue]] . Oct 24 at 12:55

Here's how to drive Brett's and belisarius's point home. Let's modify your original code a bit so we can see exactly what things are passed to your ColorFunction:

Reap[ListLinePlot[{2, 4, 6, 8, 10, 12},
ColorFunction -> Function[{x, y}, Sow[x]; If[x <= 3, Blue, Red]]]]


We obtain your erroneous plot as the first component of a list, and the list of all the values passed to your ColorFunction: {{0., 0.2, 0.4, 0.6, 0.8, 1.}} as the second component. Effectively, what was done is to apply Rescale[] to the original list you plotted (i.e. Rescale[N@{2, 4, 6, 8, 10, 12}]). That's because ColorFunctionScaling is by default set to True:

Options[ListLinePlot, ColorFunctionScaling]
{ColorFunctionScaling -> True}


Let's see what happens if we disable ColorFunctionScaling:

ListLinePlot[{2, 4, 6, 8, 10, 12},
ColorFunction -> Function[{x, y}, If[x <= 3, Blue, Red]],
ColorFunctionScaling -> False] Note the nice purplish shade in between 3 and 4, showing that the color interpolation is working nicely.

• How would one go about removing the color interpolation? Oct 4 '16 at 19:51

You can also use Mesh + MeshShading

ListLinePlot[{2, 4, 6, 8, 10, 12}, MeshStyle -> PointSize,
Mesh -> {{3}}, MeshShading -> {Blue, Red}] If you need to add PlotMarkers

Show[%, ListPlot[{2, 4, 6, 8, 10, 12}, PlotStyle->Green,  PlotMarkers-> {Automatic, 16}]] 