在 pgfplots 中使用线和点之间的间隙时的标签

在 pgfplots 中使用线和点之间的间隙时的标签

这是一个后续问题:pgfplots 中线和点之间的间隙,类似于 gnuplot 中的 pointintervalbox。我想在图中甚至在 y 轴上添加图例。不幸的是,这不适用于“不连续线”代码:

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.12}
\makeatletter
\pgfplotsset{
discontinuous line/.code={
    \pgfkeysalso{mesh, shorten <=#1, shorten >=#1}
    \def\pgfplotsplothandlermesh@VISUALIZE@std@fill@andor@stroke{%
        \pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{fill path}%
        \pgfplotsplothandlermesh@definecolor
        \pgfusepath{stroke}
        \pgfplotsplothandlermesh@show@normals@if@configured
    }%
},
discontinuous line/.default=1.5mm
}
\makeatother
\begin{document}
\begin{tikzpicture}

\begin{axis}[
axis background/.style={
    shade,bottom color=gray!50,top color=white
},
legend pos=north west,
xlabel=$x$,
ylabel=\ref{dataone}\ one  \ref{datatwo}\ two
]
\addplot [discontinuous line, black, mark=*] table {
0 5
1 3
2 4
3 8
4 0
};
\label{dataone}
\addlegendentry{one}
\addplot [discontinuous line=3mm, red, mark=square] table {
0 1
2 5.5
3 7.25
4 8
};
\label{datatwo}
 \addlegendentry{two}
\end{axis}
\end{tikzpicture}
\end{document}

得出的结果是:

在此处输入图片描述

有人知道如何获得正确的图例吗?谢谢,问候!

答案1

要修复图例,您需要重新定义legend image code/.code

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.12}
\makeatletter
\pgfplotsset{
    discontinuous line/.code={
        \pgfkeysalso{mesh, shorten <=#1, shorten >=#1,
        legend image code/.code={
        \draw [##1, shorten <=0cm] (-#1,0cm) -- (0.3cm,0cm);
        \draw [only marks] plot coordinates {(0.3cm,0cm)};
        \draw [##1, shorten >=0cm] (0.3cm,0cm) -- (0.6cm+#1,0cm);
        }}
        \def\pgfplotsplothandlermesh@VISUALIZE@std@fill@andor@stroke{%
            \pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{fill path}%
            \pgfplotsplothandlermesh@definecolor
            \pgfusepath{stroke}
            \pgfplotsplothandlermesh@show@normals@if@configured
        }%
    },
    discontinuous line/.default=1.5mm
}
\makeatother
\begin{document}
\begin{tikzpicture}

\begin{axis}[
axis background/.style={
    shade,bottom color=gray!50,top color=white
},
legend pos=north west,
xlabel=$x$,
ylabel=\ref{dataone}\ one  \ref{datatwo}\ two
]
\addplot [discontinuous line, black, mark=*] table {
0 5
1 3
2 4
3 8
4 0
};
\label{dataone}
\addlegendentry{one}
\addplot [discontinuous line=3mm, red, mark=square] table {
0 1
2 5.5
3 7.25
4 8
};
\label{datatwo}
 \addlegendentry{two}
\end{axis}
\end{tikzpicture}
\end{document}

相关内容