pgfplots 如何正确放置节点

pgfplots 如何正确放置节点

在此处输入图片描述

代码生成的图片如下,我遇到了两个问题。

(1)点上方的数字重叠

(2)数字精度不正确,例如我想要 0.913,而不是 0.91

对于第一个问题,我尝试了“节点附近的坐标对齐”,但没有得到很好的结果。有办法解决这个问题吗?

\documentclass[12pt]{article}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{filecontents}
\pagestyle{empty}

\begin{filecontents}{x.dat}
1,0.304313797
2,0.558012673
3,0.741302281
4,0.851281192
5,0.912940189
6,0.945961019
7,0.964838045
8,0.975736752
9,0.982694892
\end{filecontents}

\begin{document}
    \begin{tikzpicture}
        \begin{axis}[
            axis x line=bottom,
            axis y line=left,
            xlabel={Query Length},
            ylabel={Percentage},
            xmin=0,
            ymin=0,
            xmax=10,
            ymax=1,
            xtick={0,1,2,3,4,5,6,7,8,9},
            ytick={0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9},
            tick align=inside,
            nodes near coords,
            %nodes near coords align=horizontal,
            ]
            \addplot table[x index=0, y index=1, col sep=comma,mark=none]
            {x.dat};
        \end{axis}
    \end{tikzpicture}
\end{document}

答案1

您可以使用 来设置精度/pgf/number format=3。为了使数字合适,您可以选择较小的字体并使图更宽一些。为了更好地对齐,您可以使用anchor=-\coordindex*10,这将使第一个节点与0锚点对齐(即east),第二个节点与-10锚点对齐(略低于east),依此类推。

\documentclass[12pt]{article}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{filecontents}
\pagestyle{empty}

\begin{filecontents}{x.dat}
1,0.304313797
2,0.558012673
3,0.741302281
4,0.851281192
5,0.912940189
6,0.945961019
7,0.964838045
8,0.975736752
9,0.982694892
\end{filecontents}

\begin{document}
    \begin{tikzpicture}
        \begin{axis}[
            axis x line*=bottom,
            axis y line*=left,
            xlabel={Query Length},
            ylabel={Percentage},
            xmin=0,
            ymin=0,
            xmax=10,
            ymax=1,
            width=10cm, height=6cm,
            xtick={0,1,2,3,4,5,6,7,8,9},
            ytick={0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9},
            tick align=inside,
            nodes near coords,
            every node near coord/.append style={
                font=\scriptsize,
                /pgf/number format/precision=3,
                anchor=-\coordindex*10}
            ]
            \addplot table[x index=0, y index=1, col sep=comma,mark=none]
            {x.dat};
        \end{axis}
    \end{tikzpicture}
\end{document}

相关内容