Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

This question leads on from the recent question What are the standard colors for plots in Mathematica?

There it was determined that the default color palette used by Plot is equivalent to ColorData[1] (see the note at the end). This can be changed through the use of the option PlotStyle.

My question is how can we make, e.g., the default color palette be ColorData[3] and have this default survive manual changes to other aspects of the plot styling?


So, for example, let's make a list of monomials and some dashing settings

fns = Table[x^n, {n, 0, 5}];
dash = Table[AbsoluteDashing[i], {i, 1, 6}];

Note that the default plot colors survive other choices to styling:

GraphicsRow[{Plot[fns, {x, -1, 1}], Plot[fns, {x, -1, 1}, PlotStyle -> dash]}]

default

The colors in the plot may be changed by locally setting PlotStyle, such as

Plot[fns, {x, -1, 1}, PlotStyle -> ColorData[3, "ColorList"]]

or by setting the default options. Let's do that and run the GraphicsRow command again:

SetOptions[Plot, PlotStyle -> ColorData[3, "ColorList"]];
GraphicsRow[{Plot[fns, {x, -1, 1}], Plot[fns, {x, -1, 1}, PlotStyle -> dash]}]

ColorList 3

Note that the new colors in the default plot style is overwritten by the use of PlotStyle -> dash. This can be manually fixed, in this case, with Transpose[{dash, ColorData[3, "ColorList"][[1 ;; 6]]}], but you don't want to do that every time.

Changing the default PlotStyle will always have this problem. You'd expect there to be a default ColorData or color scheme setting somewhere, but I have been unable to find it.


Note that running the hack

Unprotect[ColorData];
ColorData[1] := ColorData[3]
ColorData[1, a__] := ColorData[3, a]
Protect[ColorData];

does not fix the default plot colors. Which probably means that the default internals of Plot does not make an explicit call to ColorData...


It's also interesting to note that when running a Trace[Plot[...],TraceInternal -> True] the colors seem to appear out of nowhere! I looked at such a trace in trying to answer this recent SO question related to how Mathematica determines the number of lines and thus colors it needs in a plot.

share|improve this question

migrated from stackoverflow.com Apr 24 '12 at 19:04

This question came from our site for professional and enthusiast programmers.

add comment

4 Answers

up vote 22 down vote accepted

Note: It has been reported by multiple users that this at present doesn't work in version 9. (I wrote it in version 7.) If anyone has time to look into that and seek a solution please do.


The following updated solution is based on the existing solutions from Janus and belisarius, but I consider it an improvement.

Corrected to work with Plot[..., {PlotStyle -> ...}] , and to move the assignment from Rule.


Supporting functions

ClearAll[toDirective, styleJoin]

toDirective[{ps__} | ps__] := 
  Flatten[Directive @@ Flatten[{#}]] & /@ {ps}

styleJoin[style_, base_] :=
  Module[{ps, n},
    ps = toDirective /@ {PlotStyle /. Options[base], style};
    ps = ps /. Automatic :> Sequence[];
    n = LCM @@ Length /@ ps;
    MapThread[Join, PadRight[#, n, #] & /@ ps]
  ]

Main function

pp is the list of Plot functions you want to affect.

sh is needed to handle pass-through plots like LogPlot, LogLinearPlot, DateListLogPlot, etc.

pp = {Plot, ListPlot, ParametricPlot, ParametricPlot3D};

Unprotect /@ pp;

(#[a__, b : OptionsPattern[]] :=
   Block[{$alsoPS = True, sh},
         sh = Cases[{b}, ("MessagesHead" -> hd_) :> hd, {-2}, 1] /. {{z_} :> z, {} -> #};
         With[{new = styleJoin[OptionValue[PlotStyle], sh]}, #[a, PlotStyle -> new, b]]
       ] /; ! TrueQ[$alsoPS]
) & /@ pp;

Usage

Now different plot types may be individually styled as follows:

SetOptions[Plot, PlotStyle -> ColorData[3, "ColorList"]];

Or in groups (here using pp defined above):

SetOptions[pp, PlotStyle -> ColorData[3, "ColorList"]];

PlotStyle options are then automatically added:

fns = Table[x^n, {n, 0, 5}];
dash = Table[AbsoluteDashing[i], {i, 1, 6}];

Plot[fns, {x, -1, 1}, PlotStyle -> dash]

enter image description here


Plot[...] and Plot[..., PlotStyle -> Automatic] are consistent:

  Plot[fns, {x, -1, 1}],
  Plot[fns, {x, -1, 1}, PlotStyle -> Automatic]

enter image description here enter image description here


Pass-through plots (those that call Plot, ListPlot or ParametricPlot) can be given their own style:

SetOptions[LogPlot, PlotStyle -> ColorData[2, "ColorList"]];

LogPlot[{Tanh[x], Erf[x]}, {x, 1, 5}]
LogPlot[{Tanh[x], Erf[x]}, {x, 1, 5}, PlotStyle -> {{Dashed, Thick}}]

enter image description here enter image description here


PlotStyle handling can be extended to different Plot types.

I included ParametricPlot3D above as an example:

fns = {1.16^v Cos[v](1 + Cos[u]), -1.16^v Sin[v](1 + Cos[u]), -2 1.16^v (1 + Sin[u])};

ParametricPlot3D[fns, {u, 0, 2 Pi}, {v, -15, 6},
  Mesh -> None, PlotStyle -> Opacity[0.6], PlotRange -> All, PlotPoints -> 25]

enter image description here


Implementation note

As it stands, resetting SetOptions[..., PlotStyle -> Automatic] will revert the colors to the original defaults. If this behavior is undesirable, the code can be modified to give a different default color, in the manner of Janus' also function, upon which my styleJoin is clearly based.

share|improve this answer
    
That's really good - it works well/smoothly. How did you find out about the "MessagesHead" thing -- that looks pretty obscure. I was really hoping that you'd found some way to use System`Private`$PlotStyleFunction, but never mind. I have two small problems with the code. (1) As you pointed out in @belisarius' answer, changing the colors of the Plot does not effect the colours of the filling. It would be possible to hack this with FillingStyle - but not really necessary. –  Simon Apr 14 '11 at 12:02
    
(2) I find associating a plotting rule with a UpValue on Rule a bit perverse. It also leads to the problem that @Sasha pointed out, since Rule is too deep for a pattern match to his example. This can be fixed by making a loop that produces a normal DownValue for each h in pp. This can also be designed to fix the problem that Sasha pointed out. Fix this issue and you get the bounty - since it is probably the best "simple" solution that is possible. –  Simon Apr 14 '11 at 12:05
1  
@Simon, by the way, I may have to add "I code perverse Mathematica" to my profile. ;-p –  Mr.Wizard Apr 14 '11 at 12:14
3  
@Mr.Wizard: It looks fine (+125)! A lot more solid than the previous version. I'm sure that this was some of the hardest 100pts that you've earned. And since your solution built off that of @Janus and @Belisarius, I feel like they should share in the bounty. So everyone who has voted up Mr.Wizards answer, go and vote up Janus' and Belisarius' answers!! –  Simon Apr 14 '11 at 23:17
1  
@Simon, thank you! The rep points are nice, but the real reward is knowing I helped. :-) –  Mr.Wizard Apr 15 '11 at 9:31
show 8 more comments

The most likely source of style data, in my opinion, is:

System`Private`$PlotStyleFunction[5]
{{Hue[0.67, 0.6, 0.6]},
 {Hue[0.906068, 0.6, 0.6]},
 {Hue[0.142136, 0.6, 0.6]},
 {Hue[0.378204, 0.6, 0.6]},
 {Hue[0.614272, 0.6, 0.6]}}

However, using Unprotect and changing this function does not effect the desired change in Plot. Perhaps the call is out of reach to normal methods.

share|improve this answer
    
Mr.W: It did look promising - but doesn't actually seem do do anything. Have you looked at Trace with TraceInteral->True? I discovered GraphicsPerformanceTuningDump`colors` that way... but it also seems to be/do nothing. Another interesting thing to look at is the output of DeleteCases[Table[{x, Names[x <> "Color*", IgnoreCase -> True]}, {x, Contexts[]}], {_, {}}] // Column... There might be something useful there, but I haven't found it yet (or figured out the right way of using it). –  Simon Apr 9 '11 at 9:05
    
Mma 7 does not appear to have "Graphics`PerformanceTuningDump`colors`" unless I am doing it wrong. When you say $PlotStyleFunction doesn't do anything, do you mean with regard to Plot? Because it certainly does give the right output on my system. (editing post to include that...) –  Mr.Wizard Apr 9 '11 at 9:22
1  
I see, nice! That matches exactly the colors used by Plot -- unlike ColorData[1,"ColorList"] which is out by 10^-16 in some cases. System`Private`$PlotStyleFunction[n, lst] gives a list of styles n long where extra styles in lst are "Riffled" into it. This behaviour can be easily emulated, but changing $PlotStyleFunction (either as a DownValue or a pure function OwnValue) doesn't seem to make any difference to Plot... :( –  Simon Apr 10 '11 at 0:08
    
@Simon, you see why I was excited, and then disappointed. I wonder if that actually is the right function, but if it is called at a level lower than DownValues/OwnValues and thereby out of reach. Do you know if this is possible? –  Mr.Wizard Apr 10 '11 at 2:25
2  
@Mr.Wizard When searching the string $PlotStyleFunction in the Mathematica's directory by Total Commander I have found four files in the "C:\Program Files\Wolfram Research\Mathematica\7.0\SystemFiles\Kernel\" subdirectories: {Binaries\Windows-x86-64\mathdll.dll,Binaries\Windows\mathdll.dll,SystemResourc‌​es\Windows-x86-64\Explore\PlotExplorer.mx,SystemResources\Windows\Explore\PlotExp‌​lorer.mx}. HTH. –  Alexey Popkov Apr 11 '11 at 12:18
show 4 more comments

This is work in progress, I'm posting it because I'm not sure to be able to finish it, and perhaps someone wants to.

The idea is to combine the wonderful Janus's solution with this nice trick to redefine the Plot[ ] standard behavior.

The program below works for a large subset of the help page for Plot[ ], but fails for two or three. The code is not tidied up, just a draft with leftovers.

Unprotect[Plot];
Plot[argsANDopts___] :=
  Block[
    {$inMsg = True, result, also, canonicalPlotStyle, opts, args, 
     optPstyle},

    If[(opts = 
        FilterRules[Cases[{argsANDopts}, _Rule], Options[Plot]]) == {},
     opts = {Axes -> (Axes /. Options[Plot])}];(*Anything not null*)
    args = Cases[{argsANDopts}, Except@_Rule];

    If[(optPstyle = Cases[opts, Rule[PlotStyle, y__] :> y]) == {}, 
     optPstyle = (PlotStyle /. Options[Plot])];

    canonicalPlotStyle[ps_] := 
     Replace[ps, {a_List :> (Flatten[Directive @@ Flatten[{#}]] &) /@ 
         a, a_ :> {Flatten@Directive[a]}}];

    also[plotstyle_] := 
     Module[{ps, n}, 
      ps = canonicalPlotStyle /@ {(PlotStyle /. Options[Plot]) /. 
          Automatic :> ColorData[1, "ColorList"], plotstyle};
      n = LCM @@ (Length /@ ps);
      Join @@@ Transpose[Flatten[Table[#, {n/Length[#]}], 1] & /@ ps]];

    (*Print@opts;
    Print@args;
    Print@optPstyle;
    Print@Evaluate@also[opts];*)
    result = Plot[
      Evaluate@Sequence@@args,
      PlotStyle -> also[optPstyle],
      Evaluate@Sequene@@opts
      ];
    result

    ] /; ! TrueQ[$inMsg];
SetOptions[Plot, PlotStyle -> ColorData[3, "ColorList"]];
Protect[Plot];

samples:

enter image description here

Does not work for:

Plot[{Sin[x], Sin[2 x], Sin[3 x]}, {x, 0, 2 Pi}, 
 PlotStyle -> {Red, Green, Blue}]
share|improve this answer
    
+1 for still using the magic variable $inMsg! I'm overrun at the moment, so will look more carefully at the code on the weekend... –  Simon Mar 24 '11 at 1:27
add comment

Here is one take on it -- the hard part was estimating how the PlotStyle option is turned into a list of directives. I think this works as the internal implementation:

canonicalPlotStyle::usage = 
  "Turn a PlotStyle option into the canonical form {_Directive...}";
canonicalPlotStyle[ps_] := Replace[ps, {
   a_List :> (Flatten[Directive @@ Flatten[{#}]] &) /@ a,
   a_ :> {Flatten@Directive[a]}}]

Building on canonicalPlotStyle it's now just a matter of combining two lists of unequal length:

also::usage = 
  "Combines a specified plotstyle with the current defaults as \
  specified by Options.";
also[plotstyle_] := Module[{ps, n},
  ps = canonicalPlotStyle /@ {
     (PlotStyle /. Options[Plot]) /. Automatic :> ColorData[1, "ColorList"],
     plotstyle};
  n = LCM @@ (Length /@ ps);
  Join @@@ Transpose[Flatten[Table[#, {n/Length[#]}], 1] & /@ ps ]]

This does require you to call the function when you plot, but I couldn't see any way around that part:

SetOptions[Plot, PlotStyle -> ColorData[3, "ColorList"]];
GraphicsRow[{Plot[fns, {x, -1, 1}], 
  Plot[fns, {x, -1, 1}, PlotStyle -> also@dash]}]

output from above code

HTH

share|improve this answer
    
As you can see, I'm using the defaults from Plot no matter where also is used. It might actually be nicer to use Options associated with also. This would also remove any need to fiddle with Options for Plot... –  Janus Mar 23 '11 at 3:24
    
Nice! +1. I think I prefer keeping the options associated with Plot (or which ever plotting function you want to use also with) so that it behaves as close to normal as possible. Obviously, it's not quite the answer I'm hoping for (ie a simple setting for a default color scheme), but it's still useful. –  Simon Mar 23 '11 at 4:10
    
Two small problems. 1) also overrides any manually set colors in the plot. This is simply fixed by reversing the order of terms in ps putting the locally supplied options last. 2) You need also every time you make a plot using a manual PlotStyle setting -- a little annoying, but not a deal breaker! –  Simon Mar 23 '11 at 4:13
    
@Simon -- Thanks for catching the ordering bug. I actually thought it had to be the way I did it, maybe inspired by rules. Will edit above. –  Janus Mar 23 '11 at 5:01
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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