3
$\begingroup$

Is there a way to put a legend mark with a color function rainbow?

For example:

legend2 = 
 Grid[{{Graphics[{Red, Thick, Line[{{0, 0}, {2, 0}}]}, 
     ImageSize -> 5], "u"}}]
u[x_] := x
Plot[u[x], {x, 0, 1}, ColorFunction -> "Rainbow", 
 PlotLegends -> Placed[legend2, {{1.05, 0.5}, {0, 0.5}}]]

enter image description here

In this case the plot marker is red. Is there a way to put a rainbow scale like the function?

$\endgroup$
  • $\begingroup$ I don't want a bar. I want a line (like the image) but instead the color red, a rainbow color. $\endgroup$ – Mateus Jul 9 at 22:04
5
$\begingroup$
u[x_] := x
sparkline = Plot[0, {x, 0, 1},
   ColorFunction -> (ColorData[ "Rainbow"][#] &), 
   PlotStyle -> Thick, 
   PlotTheme -> "Sparkline", Axes -> False];

Plot[u[x], {x, 0, 1}, 
  ColorFunction -> "Rainbow", 
  PlotStyle -> Thick, 
  PlotLegends -> Labeled[sparkline, "u", Right]]

enter image description here

An alternative ways is to use {sparkline} with the (undocumented) option "LegendItem" inside LineLegend:

Plot[u[x], {x, 0, 1}, 
 ColorFunction -> "Rainbow", 
  PlotStyle -> Thick, 
  PlotLegends -> LineLegend[Automatic, {u}, "LegendItem" -> {sparkline}]]

enter image description here

Variations on the same idea:

colorfunctions = {"Rainbow", "SolarColors"};
functions = {Sin[x], Cos[x]};

sparklines = MapThread[Plot[#, {x, 0, 2 Pi}, 
     ColorFunction -> #2, PlotStyle -> Thick, 
     PlotTheme -> "Sparkline", Axes -> False] &,
  {functions, colorfunctions}];

Show[MapThread[Plot[#, {x, 0, 2 Pi}, 
     ColorFunction -> #2, PlotStyle -> Thick, 
     PlotLegends -> LineLegend[Automatic, {TraditionalForm @ #}, 
        "LegendItem" -> {#3}, LegendMarkerSize -> Large]] &,
   {functions, colorfunctions, sparklines}]]

enter image description here

$\endgroup$
2
$\begingroup$

You can use LegendLayout to modify the Line[] in LineLegend:

ClearAll[cfline];
cfline[cf_String] := cfline[ColorData@cf];
cfline[cf_][pairs_] := Grid[
   pairs /. 
    Line[{a_, b_}] :> 
     Line[Subdivide[a, b, 20], 
      VertexColors -> cf /@ Subdivide[0., 1., 20]]
   ];

Plot[u[x], {x, 0, 4},
 ColorFunction -> "Rainbow", 
 PlotLegends -> LineLegend["Expressions", LegendLayout -> cfline@"Rainbow"]]

enter image description here

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