pgfplots:如何繪製一條線到座標系的末尾

pgfplots:如何繪製一條線到座標系的末尾

在此輸入影像描述

如何在 y 方向上精確地繪製一條垂直於座標系末端的線?

·請注意,(自動設定的)“ymax=10”可以更改(我不知道ymax=<value>,因為表包含隨機數。)

·請注意,給出了 x 值“6”(通常作為特殊值從表中讀出)。

\documentclass[margin=5mm, tikz]{standalone}
\usepackage{pgfplots}
\begin{document}

\pgfplotstableread[col sep=comma]{
0, 0
1, 0
2, 0
3, 1
4, 3
5, 2
6, 5
7, 0
8, 1
12,10
13,5
}\mytable


\begin{tikzpicture}[]
\begin{axis}[
xmin=0, ymin=0, 
]
\addplot[mark=*] table[]{\mytable};

\addplot[densely dashed, red] coordinates{(6,0) (6,10)};
\end{axis}
\end{tikzpicture}
\end{document}

答案1

\documentclass[tikz, border=1cm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\pgfplotstableread[col sep=comma]{
0, 0
1, 0
2, 0
3, 1
4, 3
5, 2
6, 5
7, 0
8, 1
12,10
13,5
}\mytable
\begin{tikzpicture}
\begin{axis}[
xmin=0, ymin=0, 
]
\addplot[mark=*] table[]{\mytable};
\draw[red, ultra thick, densely dashed] (6,0) -- (6,0|-current axis.north);
\draw[green, densely dashed] (6,0) -- (6,\pgfkeysvalueof{/pgfplots/ymax});
\end{axis}
\end{tikzpicture}
\end{document}

在此輸入影像描述

答案2

兩個想法(compat無論如何,您都應該將該選項設為最近的版本):

  1. 使用update limits=false防止線的座標延伸 y 軸範圍:
\documentclass[border=10pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\begin{document}

\pgfplotstableread[col sep=comma]{
0, 0
1, 0
2, 0
3, 1
4, 3
5, 2
6, 5
7, 0
8, 1
12,10
13,5
}\mytable

\begin{tikzpicture}[]
\begin{axis}[
    xmin=0, ymin=0, 
]
\addplot[mark=*] table[]{\mytable};

\addplot[densely dashed, red, update limits=false] coordinates{(6,0) (6,11)};

\end{axis}
\end{tikzpicture}
\end{document}
  1. 使用指令繪製線條\draw
\documentclass[border=10pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\begin{document}

\pgfplotstableread[col sep=comma]{
0, 0
1, 0
2, 0
3, 1
4, 3
5, 2
6, 5
7, 0
8, 1
12,10
13,5
}\mytable

\begin{tikzpicture}[]
\begin{axis}[
    xmin=0, ymin=0
]
\addplot[mark=*] table[]{\mytable};

\draw[densely dashed, red] 
    (6,0 |- {yticklabel cs:0}) -- (6,0 |- {yticklabel cs:1});

% alternatively:
% \draw[densely dashed, red] 
%    (6,\pgfkeysvalueof{/pgfplots/ymin}) -- (6,\pgfkeysvalueof{/pgfplots/ymax});

\end{axis}
\end{tikzpicture}
\end{document}

兩個程式碼範例產生相同的輸出:

在此輸入影像描述

相關內容