Share
Share

Reputation: 505

How to add legends for multiple plots in mathematica?

I have code that looks like this

    gx = n * k0 * (1 - ((n/a)^ beta)
    Show[
    Plot[gx /. {k0 -> 0.5, beta -> 5, n -> 9, a -> 1}, {n, 0, 12}, PlotRange -> {{0, 12}, {0, 5}}, PlotLabels -> {"r0 = 0.5"}],
    Plot[gx /. {k0 -> 0.5, beta -> 0.5, n -> 9, a -> 1}, {n, 0, 12}, PlotRange -> {{0, 12}, {0, 5}}, PlotLabels -> {"r0 = 0.8"}]
        ]

However, I get the labels one on top of another and not labelled distinctly.

Alternately, I tried used legends

Show[
Plot[gx /. {k0 -> 0.5, beta -> 5, n -> 9, a -> 1}, {n, 0, 12}, PlotRange -> {{0, 12}, {0, 5}}],
Plot[gx /. {k0 -> 0.5, beta -> 0.5, n -> 9, a -> 1}, {n, 0, 12}, PlotRange -> {{0, 12}, {0, 5}}],
PlotLegends -> {"beta = 5", "beta=0.5"}
    ]

For which I get an error that says could not combine graphic objects in Show

Any suggestions on how I can work on these?

Upvotes: 2

Views: 3848

Answers (1)

Chris Degnen
Chris Degnen

Reputation: 8655

Three variations shown here.

gx = n*k0*(1 - ((n/a)^beta));

Show[
 Plot[gx /. {k0 -> 0.5, beta -> 5, n -> 9, a -> 1}, {n, 0, 12},
  PlotRange -> {{0, 12}, Automatic}, PlotLabels -> {"beta = 5"}],
 Plot[gx /. {k0 -> 0.5, beta -> 0.5, n -> 9, a -> 1}, {n, 0, 12},
  PlotRange -> {{0, 12}, Automatic}, PlotLabels -> {"beta=0.5"}]]

enter image description here

Plot[
 {gx /. {k0 -> 0.5, beta -> 5, n -> 9, a -> 1},
  gx /. {k0 -> 0.5, beta -> 0.5, n -> 9, a -> 1}},
 {n, 0, 12}, PlotRange -> {{0, 12}, Automatic},
 PlotLegends -> {"beta = 5", "beta=0.5"}]

enter image description here

Legended[Show[
  Plot[gx /. {k0 -> 0.5, beta -> 5, n -> 9, a -> 1}, {n, 0, 12},
   PlotStyle -> ColorData[97][1], PlotRange -> {{0, 12}, Automatic}],
  Plot[gx /. {k0 -> 0.5, beta -> 0.5, n -> 9, a -> 1}, {n, 0, 12},
   PlotStyle -> ColorData[97][2], PlotRange -> {{0, 12}, Automatic}]],
 LineLegend[ColorData[97] /@ {1, 2}, {"beta = 5", "beta=0.5"}]]

enter image description here

Upvotes: 2

Related Questions