ラベルを追加し、リストの反復を通じてパスを構築する

ラベルを追加し、リストの反復を通じてパスを構築する

物理学の授業でメタポストを使ってグラフを作成する必要がありました (下記参照)。私がお聞きしたいのは、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

これは、コードの最後の部分を置き換えるもう 1 つの (遅い) 試みです。以前と同様に、1 つの 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;

関連情報