7
$\begingroup$

I have a set of three plots and I want to define the line style for these plots, but I do not want to define this inside the plot function, but outside the plot function, like assigning to a variable. how to do this?

 style1 = PlotStyle -> {Black, Thickness[0.004], 
   AbsoluteDashing[{2, 7}]}
style2 = PlotStyle -> {Black, Thickness[0.004], 
   AbsoluteDashing[{8, 20}]}
style3 = PlotStyle -> {Black, Thickness[0.004], 
   AbsoluteDashing[{4, 18, 40}]}
p1 = Plot[Sin[π*x], {x, 0, 1}, style1];
p2 = Plot[Sin[2 π*x], {x, 0, 1}, style2];
p3 = Plot[Sin[3 π*x], {x, 0, 1}, style3];
Show[p1, p2, p3, PlotRange -> All]
$\endgroup$

2 Answers 2

6
$\begingroup$

Wrap style1,style2 and style3 with Evaluate:

p1 = Plot[Sin[π*x], {x, 0, 1}, Evaluate@style1];
p2 = Plot[Sin[2 π*x], {x, 0, 1}, Evaluate@style2];
p3 = Plot[Sin[3 π*x], {x, 0, 1}, Evaluate@style3];

Show[p1, p2, p3, PlotRange -> All]

enter image description here

Alternatively, force evaluation by passing style1,style2 and style3 as arguments:

p1 = Plot[Sin[π*x], {x, 0, 1}, #]& @ style1;
p2 = Plot[Sin[2 π*x], {x, 0, 1}, #]& @ style2;
p3 = Plot[Sin[3 π*x], {x, 0, 1}, #]& @ style3;
Show[p1, p2, p3, PlotRange -> All]

same picture

You can also inject the styles using With:

p1 = With[{style1=style1},Plot[Sin[π*x], {x, 0, 1},style1]];
p2 =  With[{style2=style2},Plot[Sin[2 π*x], {x, 0, 1},style2]];
p3 = With[{style3=style3}, Plot[Sin[3 π*x], {x, 0, 1},style3]];
Show[p1, p2, p3, PlotRange -> All]

same picture

$\endgroup$
3
$\begingroup$

The most straightforward way of general style definition in MMA 12 is:

st=Sequence["color","thickness", "any-of-other-style-definitions"];
Plot[f[x],{x,x0,xl},st, PlotRange->All]

The Sequence produces the true sequence of definitions which are not wrapped by any additional figure brackets { }. Thus, one can use it with any following options like PlotRange or something else without Evaluate.

$\endgroup$
2
  • 1
    $\begingroup$ tried style1 = Sequence[ PlotStyle -> {Black, Thickness[0.004], AbsoluteDashing[{2, 7}]}]; p1 = Plot[Sin[\[Pi]*x], {x, 0, 1}, style1]? $\endgroup$
    – kglr
    Sep 28, 2019 at 7:50
  • $\begingroup$ @kglr, it is strange. As I know, the Sequence is specially created for such purposes.. $\endgroup$
    – Rom38
    Sep 28, 2019 at 8:16

Your Answer

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

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