TransWikia.com

How should I include PlotLegends in the given code to get the given plot?

Mathematica Asked on May 9, 2021

How can I include PlotLegends in this code

{data1, data2} = Transpose[Table[{2, 8/n}, {n, 20}]];

a = ListLogPlot[data1, Frame -> True, 
   PlotMarkers -> Style["[FilledDiamond]", 10, Red]];
b = ListLogPlot[data2, Frame -> True, Joined -> True, 
   PlotStyle -> Black, Mesh -> All];

Show[a, b, PlotRange -> All, Axes -> None]

to give me a plot such the legends are like this picture

enter image description here

and

enter image description here

One Answer

You can do all in a single ListLogPlot:

ListLogPlot[{data1, data2}, 
 Joined -> {False, True}, 
 Frame -> True, 
 PlotMarkers -> {{"◆", 10}, {"●", 10}}, 
 PlotStyle -> {Red, Black}, 
 Mesh -> All, 
 PlotLegends -> {"first", "second"}]

enter image description here

Altenatively, add the option PlotLegends in each plot. Show combines the legends automatically:

a = ListLogPlot[data1, Frame -> True, 
   PlotMarkers -> Style["◆", 10, Red], 
   PlotLegends -> {"first"}];

b = ListLogPlot[data2, Frame -> True, Joined -> True, 
   PlotStyle -> Black, Mesh -> All, 
   PlotLegends -> LineLegend[{"second"}, LegendMarkers -> {Automatic, 10}]];

Show[a, b, PlotRange -> All, Axes -> None]

![enter image description here

Update: To get a picture like the second picture in OP we can use PlotStyle. If we specify different colors for points and lines in b using, say,

   PlotStyle ->  Directive[CapForm["Round"], AbsoluteThickness[5], Black, 
     LineColor -> Blue]

the lines and markers in the legend are automatically colored to match the specification in PlotStyle.

So, we can use the first approach as follows:

ListLogPlot[{data1, data2}, Joined -> {False, True}, Frame -> True, 
 PlotMarkers -> {{"◆", 16}, {"●", 14}}, 
 PlotStyle -> {Red, Directive[CapForm["Round"], AbsoluteThickness[5], Black, 
    LineColor -> Blue]},
 Mesh -> All, PlotLegends -> {"first", "second"}]

enter image description here

And modify the second approach as follows:

a = ListLogPlot[data1, Frame -> True, 
   PlotMarkers -> Style["◆", 14, Red], 
   PlotLegends -> {"first"}];

b = ListLogPlot[data2, Frame -> True, Joined -> True, 
   PlotStyle ->  Directive[CapForm["Round"], AbsoluteThickness[5], Black, 
     LineColor -> Blue], 
   Mesh -> All, 
   MeshStyle -> AbsolutePointSize[9], 
   PlotLegends -> LineLegend[{"second"}, LegendMarkers -> {Automatic, 14}]];

Show[a, b, PlotRange -> All, Axes -> None]

enter image description here

Correct answer by kglr on May 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP