我不确定为同一问题添加另一个不同答案的规则是什么。但这是另一种不同的方法。如果我应该将此添加到我的第一个答案中,我可以这样做。
您可以使用文本命令手动添加文本标签。我认为它看起来更好。这是一种方法:
Clear[x];
funs = {Exp[x], 2^x, 3^x};
funNames = Style[#, 12] & /@ funs;
(*the x-axis plot range used *)
from = -5; to = 2;
(* generate the coordinates at the end of the plot lines*)
pos = Map[{to, #} &, funs /. x -> to];
(*generate the text labels *)
text = Map[Text[#[[1]], #[[2]], {-1, 0}] &, Thread[{funNames, pos}]];
绘制最终结果(在绘图范围中添加一点填充,以便
添加的标签完全可见)
Plot[funs, {x, from, to},
PlotRangePadding -> {1, 1},
PlotStyle -> {Red, Green, Blue},
PlotRange -> All,
Epilog -> text
]
更新(1)
Sam 在下面询问了一种更简单的方法。我现在不确定。但一种更容易使用此方法的方法是创建一个函数,然后简单地调用该函数一次以生成文本标签。您可以将此函数放在您一直使用的所有其他函数的位置,然后调用它。
这里有一点:先写函数
(*version 1.1*)
myLegend[funs_List, (*list of functions to plot*)
x_, (*the independent variable*)
from_?(NumericQ[#] && Im[#] == 0 &),(*the x-axis starting plot range*)
to_?(NumericQ[#] && Im[#] == 0 &) (*the x-axis ending plot range*)
] := Module[{funNames, pos, text, labelOffset = -1.3},
(*make label names*)
funNames = Style[#, 12] & /@ funs;
(*generated the coordinates at the end of the plot lines*)
pos = Map[{to, #} &, funs /. x -> to];
(*generate the Text calls*)
text = Map[Text[#[[1]], #[[2]], {labelOffset, 0}] &,
Thread[{funNames, pos}]]
];
现在只要您想使用标签进行绘图,只需调用上述方法即可。这将只是 1-2 额外的代码行。像这样:
Clear[x]
from = -5; to = 2;
funs = {Exp[x], 2^x, 3^x};
Plot[funs, {x, from, to}, PlotRangePadding -> {1, 1},
PlotStyle -> {Red, Green, Blue}, PlotRange -> All,
Epilog -> myLegend[funs, x, from, to]]
这里有几个例子:
你可以随意修改。