我正在尝试在 pgfplots 中制作平行轴图,但在如何自动生成 x 轴标签方面遇到了困难。
下面是我正在做的事情的一个简化示例:
\documentclass[tikz]{standalone}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\begin{filecontents}{testdata.dat}
0.2,0.4,0.3,0.1,0.7
0.6,0.2,0.9,0.4,0.2
0.1,0.9,0.6,0.8,0.3
0.2,0.6,0.3,0.4,0.5
0.3,0.1,0.6,0.3,0.8
0.5,0.3,0.2,0.6,0.5
0.1,0.8,0.3,0.2,0.4
0.4,0.1,0.8,0.5,0.2
0.2,0.8,0.6,0.7,0.3
\end{filecontents}
\begin{document}
\begin{tikzpicture}
\pgfplotsset{every tick label/.append style={font=\footnotesize}}
\pgfplotstableread[col sep = comma]{testdata.dat}\data
\pgfplotstabletranspose[]\dataT{\data}
\pgfplotstablegetrowsof{\data}
\pgfmathsetmacro{\nRows}{\pgfplotsretval-1}
\begin{axis}[xtick distance=1,
xticklabels={dummy,$x_1$,$x_2$,$x_3$,$x_4$,$x_5$}, % need to change this line
xlabel=variable,
xlabel near ticks,
ylabel=scaled $x$ value,
ylabel near ticks]
\foreach \i in {0,...,\nRows}{
\addplot[blue] table [y=\i] {\dataT};
}
% Plot code
\end{axis}
\end{tikzpicture}
\end{document}
生成结果:
我的问题是,我将生成许多这样的图,但并非所有图都具有相同数量的 x 变量。我如何修改轴定义中的行以使用并根据数据文件\pgfplotstablegetcolsof{\data}
自动生成 x 标签?x_1,...,x_n
答案1
您可以使用选项定义如何打印标签xticklabel
。您可以使用
xticklabel={\pgfmathparse{\tick+1}$x_{\pgfmathprintnumber{\pgfmathresult}}$}
完整代码:
\documentclass[tikz,border=10]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\usepackage{pgfplotstable}
\begin{filecontents}{testdata.dat}
0.2,0.4,0.3,0.1,0.7
0.6,0.2,0.9,0.4,0.2
0.1,0.9,0.6,0.8,0.3
0.2,0.6,0.3,0.4,0.5
0.3,0.1,0.6,0.3,0.8
0.5,0.3,0.2,0.6,0.5
0.1,0.8,0.3,0.2,0.4
0.4,0.1,0.8,0.5,0.2
0.2,0.8,0.6,0.7,0.3
\end{filecontents}
\begin{document}
\begin{tikzpicture}
\pgfplotsset{every tick label/.append style={font=\footnotesize}}
\pgfplotstableread[col sep = comma]{testdata.dat}\data
\pgfplotstabletranspose[]\dataT{\data}
\pgfplotstablegetrowsof{\data}
\pgfmathsetmacro{\nRows}{\pgfplotsretval-1}
\begin{axis}[xtick distance=1,
xticklabel={\pgfmathparse{\tick+1}$x_{\pgfmathprintnumber{\pgfmathresult}}$}, % <--- new line
xlabel=variable,
xlabel near ticks,
ylabel=scaled $x$ value,
ylabel near ticks]
\foreach \i in {0,...,\nRows}{
\addplot[blue,mark=*] table [y=\i] {\dataT};
}
% Plot code
\end{axis}
\end{tikzpicture}
\end{document}