如何將點的 x 座標作為額外的 x 刻度?

如何將點的 x 座標作為額外的 x 刻度?

我需要將點的 x 座標作為額外的 x 刻度,但常見的方法是不合理的,因為可能有很多點並且重複它們extra x ticks很差。

\documentclass[tikz, border=1cm]{standalone}
\usepackage{pgfplots}

    \begin{document}

    %---------------------------------------------------------

            \begin{tikzpicture}[
                ]
                \begin{axis}[
                    width=\linewidth, axis lines = middle,
                    extra x ticks = {1.1, 2.2,3.3}, % irrational decision, because there can be many points
                    xtick=data,
                ]
                \addplot[] {x};
                \addplot[color=red,mark=*, only marks] coordinates {
                        (1.1,1)
                        (2.2,2)
                        (3.3,3)
                    };
                \end{axis}
            \end{tikzpicture}

    %---------------------------------------------------------
    \end{document}

答案1

如果你這樣做

xtick=data, % data points from first \addplot
extra x ticks={-4,...,4} % regularly spaced ticks

您將獲得第一個中每個點的刻度\addplot,此外還有規則間隔的刻度。但它可能會變得有點混亂。分離它們的一種方法是將座標刻度向下移動,即

xticklabel style={yshift=-15pt},
extra x tick style={tick label style={yshift=15pt}}

需要第二行,因為第一行也會影響額外的刻度標籤。

對於nodes near coords,新增point meta=x,nodes near coordsan 的選項\addplot將在該圖中的點旁邊新增 x 值。下面的程式碼演示了這兩者。

在此輸入影像描述

\documentclass[tikz, border=1cm]{standalone}
\usepackage{pgfplots}

    \begin{document}

    %---------------------------------------------------------

            \begin{tikzpicture}[
                ]
                \begin{axis}[
                    width=\linewidth, 
                    axis lines = middle,
                    xtick=data, % data points from first \addplot
                    extra x ticks={-4,...,4}, % regularly spaced ticks
                    xticklabel style={yshift=-15pt},
                    extra x tick style={tick label style={yshift=15pt}}
                ]
                \addplot[color=red,mark=*,
                         only marks,
                         point meta=x, % use x-value for nodes near coords
                         nodes near coords
                        ] coordinates {
                        (1.1,1)
                        (2.2,2)
                        (3.3,3)
                    };
                \addplot[] {x};

                \end{axis}
            \end{tikzpicture}

    %---------------------------------------------------------
    \end{document}

相關內容