我必须使用 metapost 为我的物理课程构建一个图表(见下文)。我想问的是,是否有办法像我使用 tikz 那样添加曲线及其标签:
\draw[color=red, ultra thick] (0,0) \foreach \x/\y/\text in {1/1/t=1 s, 2/2/t=2 s, 4/6/t=3 s, 6/8/t=4 s,9/8/t=5 s, 11/6/t=6 s, 13/5/t=7 s}
{
-- (\x,\y) node[above]{\small \text}
};
\startMPcode
path p;
numeric xmin, xmax, ymin, ymax;
ux := .5cm; uy := .5cm;
xmin := 0; xmax := 14;
ymin := 0; ymax := 10;
% draw tickmarks and labels on horizontal axis
for i=0 upto xmax:
draw (i,-0.05)*ux--(i,ymax)*ux withcolor 0.8white;
draw (i,-0.05)*ux--(i,0.05)*ux;
label.bot(textext(decimal(i*10)) scaled 0.7,(i,0)*ux);
endfor;
% draw tickmarks and labels on vertical axis
for i=0 upto ymax:
draw (-0.05,i)*uy--(xmax,i)*uy withcolor 0.8white;
draw (-0.05,i)*uy--(0.05,i)*uy;
label.lft(textext(decimal(i*10)) scaled 0.7,(0,i)*uy);
endfor;
%draw the axis
drawoptions(withcolor black);
drawarrow (xmin,0)*ux -- (xmax+1/2,0)*ux;
drawarrow (0,ymin)*uy -- (0,ymax+1/10)*uy;
label.bot(btex $x$ (m) etex scaled .7, (xmax*ux,-0.8*uy));
label.lft(btex $y$ (m) etex rotated(90) scaled .7, (-0.8*ux,ymax*uy));
%draw the curve and labels
pickup pencircle scaled 2pt;
p:=(0,0)--(1*ux,1*uy)--(2*ux,2*uy)--(4*ux,6*uy)--(6*ux,8*uy)--(9*ux,8*uy)--(11*ux,6*uy)--(13*ux,5*uy);
draw p withcolor red ;
dotlabel.top(btex t=1 s etex scaled 0.7, (1*ux,1*uy)) withcolor blue;
dotlabel.top(btex t=2 s etex scaled 0.7, (2*ux,2*uy)) withcolor blue;
dotlabel.top(btex t=3 s etex scaled 0.7, (4*ux,6*uy)) withcolor blue;
dotlabel.top(btex t=4 s etex scaled 0.7, (6*ux,8*uy)) withcolor blue;
dotlabel.top(btex t=5 s etex scaled 0.7, (9*ux,8*uy)) withcolor blue;
dotlabel.top(btex t=6 s etex scaled 0.7, (11*ux,6*uy)) withcolor blue;
dotlabel.top(btex t=7 s etex scaled 0.7, (13*ux,5*uy)) withcolor blue;
\stopMPcode
答案1
不确定我是否正确理解了这个问题,但这里尝试替换代码的最后一部分,这更接近于你的 tikz 代码处理它的方式:
%draw the curve and labels
pickup pencircle scaled 2pt;
i:=0;
p:=(0, 0)
for k=(1, 1), (2, 2), (4, 6), (6, 8), (9, 8), (11, 6), (13, 5):
-- (xpart(k)*ux, ypart(k)*uy)
hide(i:=i+1; dotlabel.top(textext("t=" & decimal(i) &" s"), (xpart(k)*ux, ypart(k)*uy)) withcolor blue;)
endfor;
draw p withcolor red;
答案2
这是另一个(较晚的)尝试来替换代码的最后一部分。和以前一样,它只使用一个 for 循环,但这个循环在曲线之后(顶部)绘制标签,就像您的 Tikz 程序一样,而我之前的 MetaPost 程序没有这样做。
%draw the curve and labels
pickup pencircle scaled 2pt;
picture mylabels; mylabels:=nullpicture;
i := 0;
p := (0, 0)
for k = (1, 1), (2, 2), (4, 6), (6, 8), (9, 8), (11, 6), (13, 5):
-- k xyscaled (ux, uy)
hide(i:=i+1;
addto mylabels also
thelabel.top(textext("t="&decimal(i)&" s"), k xyscaled(ux, uy)) withcolor blue)
endfor;
draw p withcolor red;
addto currentpicture also mylabels;