9
$\begingroup$

I often use Epilog to label lines within graphs, and I like to coordinate the color of the labels with the color of the lines they're labeling. This is no problem. However, I'm currently working on a project in which I need vertical connecting lines at selected places, and these should color match as well. For the life of me, I can't figure out how to do this.

Plot[{Sin[x], Sin[x + 0.5]}, {x, 0, 2*Pi}, PlotStyle -> {Blue, Red}, 
 Epilog -> {
   Line[{{2, 0}, {2, Sin[2]}}],
   Line[{{3, 0}, {3, Sin[3.5]}}]}]

enter image description here

Any help would be appreciated.

$\endgroup$
12
$\begingroup$
   Plot[{Sin[x], Sin[x + 0.5]}, {x, 0, 2*Pi}, PlotStyle -> {Blue, Red}, 
   Epilog -> {Blue, Line[{{2, 0}, {2, Sin[2]}}], Red, 
   Line[{{3, 0}, {3, Sin[3.5]}}]}]
$\endgroup$
9
$\begingroup$

kguler's method gets the job done but in anything but the simplest uses it can become a headache.

In cases like this I prefer to use either a custom plot function or a function/rule that accepts plot output and applies my changes automatically. For example:

addEpilog[g_Graphics, epi_List] :=
  With[{styles = Cases[g[[1]], {dir__, __Line} :> Directive[dir], -5]},
    Show[g, Epilog -> {styles, epi} ~Flatten~ {2}]
  ]

Now:

p = Plot[{Sin[x], Sin[x + 0.5]}, {x, 0, 2*Pi}, PlotStyle -> {Blue, Red}];

addEpilog[p,
  { Line[{{2, 0}, {2, Sin[2]}}], Line[{{3, 0}, {3, Sin[3.5]}}] }
]

Mathematica graphics

To add multiple primitives in a given style simply group them in a List:

addEpilog[p,
 {
  Line[{{#, 0}, {#, Sin[#]}}] &      /@ {2, 4, 6},
  Line[{{#, 0}, {#, Sin[# + .5]}}] & /@ {1, 3, 5}
 }
]

Mathematica graphics

$\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.