3
$\begingroup$

I want to label a ListPlot using LineLegend with the line colours corresponding to the filling. For example if I use this function to create two sparse arrays:

array[length_Integer, values_Integer] := 
 SparseArray[
  RandomSample[Range[length], values] -> 
   RandomReal[{-1, 1}, {values}], length]

When I plot them, I want to label them by filling using a line, not a point. LineLegend doesn't seem to work (LegendMarkers has no effect):

ListPlot[{array[50, 12], array[50, 15]}, PlotStyle -> Black, 
 PlotRange -> All, 
 Filling -> {{1 -> {Axis, Red}}, {2 -> {Axis, Blue}}}, 
 PlotLegends -> LineLegend[{Red, Blue}, {"1", "2"}, LegendMarkers -> Automatic]]

enter image description here

Is this expected behaviour or am I missing something really obvious here?

$\endgroup$
7
$\begingroup$

A workaround is to add HoldForm:

ListPlot[{array[50, 12], array[50, 15]}, PlotStyle -> Black, PlotRange -> All, 
 Filling -> {{1 -> {Axis, Red}}, {2 -> {Axis, Blue}}}, 
 PlotLegends -> 
  HoldForm @ LineLegend[{Red, Blue}, {"1", "2"}, LegendMarkers -> Automatic]]

enter image description here

$\endgroup$
  • $\begingroup$ AHA! Perfect - thanks! $\endgroup$ – gpap Dec 15 '16 at 8:47
1
$\begingroup$

Here is a no frills example of a legend that almost does what you want:

legend = ImageCrop@Graphics[{
     Text[Style["1-----", Blue], {0, 1/20}],
     Text[Style["2-----", Red], {0, -1/20}]
     }];
ListPlot[{array[50, 12], array[50, 15]},
 PlotStyle -> Black, PlotRange -> All,
 Filling -> {{1 -> {Axis, Red}}, {2 -> {Axis, Blue}}},
 PlotLegends -> legend]

It should be easy to draw a thick line over the dashed text, but I haven't been able to add that bit of finesse.

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