Skip to main content

plotting - Legend in a Show


I am trying to put some legends on a graph but I am not able to do that.


This is my code:


k = 1;   (* J/K *)
T = 1; (* K *)
nlm =
NonlinearModelFit[data, V, {M, n}, λ];
nlm["BestFitParameters"]
Show[ListPlot[data],
Plot[Normal[nlm], {λ, 0, 8}, PlotStyle -> Red],

Frame -> True, GridLines -> Automatic,
GridLinesStyle -> Directive[Gray, Dashed], AspectRatio -> 1.6,
ImageSize -> Large,
FrameLabel -> {"λ", "σ [MPa]"},
LabelStyle -> {FontFamily -> "Helvetica", 14}]

I tried to look on the internet already but I don´t understand how to do it. For example there is this discussion: Dynamic legends involving show


In which it looks like the same problem of mine, but I am not able to fully understand it.


I am really new with Mathematica, so please consider it.


Thanks, Fab.



EDIT: After discussing here, this is the new code which works for me. Of course as someone told me, it is not running this piece of code because you need the data but it can be really useful to understand how to have such a picture: I still need to understand how to enlarge the font of the legend, but this is another problem


k = 1;   (* J/K *)
T = 1; (* K *)

nlm = NonlinearModelFit[data, V, {M, n}, λ];
nlm["BestFitParameters"]
lgnd = Framed[
Column[{LineLegend[{Red}, {"data"}],
PointLegend[{Blue}, {Row[{"Experiment Data"}]}]}],
Background -> LightGray];

Legended[Show[ListPlot[data],
Plot[Normal[nlm], {λ, 0, 8}, PlotStyle -> Red],
Frame -> True, GridLines -> Automatic,
GridLinesStyle -> Directive[Gray, Dashed], AspectRatio -> 1.,
ImageSize -> Large,
FrameLabel -> {"λ", "σ [MPa]"},
LabelStyle -> {FontFamily -> "Helvetica", 22}],
Placed[lgnd, {0.82, 0.2}]]

Answer



For illustrative purpose (please also search site and documentation):



toy = Table[{j, j^2 + RandomReal[{-3, 3}]}, {j, -4, 4, 0.1}];
mod = LinearModelFit[toy, {1, x, x^2}, x];
lp = ListPlot[toy, PlotStyle -> Red];
modp = Plot[mod[x], {x, -4, 4}, PlotStyle -> Blue];
lgnd = Framed[
Column[{PointLegend[{Red}, {"data"}],
LineLegend[{Blue}, {Row[{"fit: ", Normal@mod}]}]}],
RoundingRadius -> 20, Background -> LightBlue];
Legended[Show[lp, modp], lgnd]


enter image description here


Comments