在 Tikz 中编写轴标签的一种简单方法是:
\foreach \x/\xtext in {-1,-0.5,0.5,1}
\draw[very thin,gray] (\x cm,1pt) -- (\x cm,-1pt) node[anchor=north] {$\xtext$};
是否有可能存在类似情况但却\x
无法\xtext
从以下相同列表中获取值?
\foreach \x in {-1,-0.5,0.5,1}/\xtext in {-10,-5,5,10}
\draw[very thin,gray] (\x cm,1pt) -- (\x cm,-1pt) node[anchor=north] {$\xtext$};
答案1
这是一段简单的代码。这是你想要的吗?
\begin{tikzpicture}
\draw[very thin,gray] (-1,0)--(1,0);
\foreach \x/\xtext in {-1/a_0,-0.5/a_1,0.5/a_2,1/a_3}{
\draw[very thin,gray] (\x cm,1pt) -- (\x cm,-1pt) node[anchor=north] {$\xtext$};
}
\end{tikzpicture}
答案2
如果您的列表来自不同的来源,那么您需要按如下方式合并它们:
\documentclass{article}
\usepackage{tikz}
\makeatletter
% \specialmergetwolists{<coupler>}{<list1>}{<list2>}{<return macro>}
% \specialmergetwolists*{<coupler>}{<listcmd1>}{<listcmd2>}{<return macro>}
\protected\def\specialmergetwolists{%
\begingroup
\@ifstar{\def\cnta{1}\@specialmergetwolists}
{\def\cnta{0}\@specialmergetwolists}%
}
\def\@specialmergetwolists#1#2#3#4{%
\def\tempa##1##2{%
\edef##2{%
\ifnum\cnta=\@ne\else\expandafter\@firstoftwo\fi
\unexpanded\expandafter{##1}%
}%
}%
\tempa{#2}\tempb\tempa{#3}\tempa
\def\cnta{0}\def#4{}%
\foreach \x in \tempb{%
\xdef\cnta{\the\numexpr\cnta+1}%
\gdef\cntb{0}%
\foreach \y in \tempa{%
\xdef\cntb{\the\numexpr\cntb+1}%
\ifnum\cntb=\cnta\relax
\xdef#4{#4\ifx#4\empty\else,\fi\x#1\y}%
\breakforeach
\fi
}%
}%
\endgroup
}
\makeatother
\begin{document}
\specialmergetwolists{/}{-1,-0.5,0.5,1}{a_0,a_1,a_2,a_3}\clist
% If the lists are in macros, use the star (*) form:
% \def\alist{-1,-0.5,0.5,1}
% \def\blist{a_0,a_1,a_2,a_3}
% \specialmergetwolists*{/}\alist\blist\clist
\begin{tikzpicture}
\draw[very thin,gray] (-1,0)--(1,0);
\foreach \x/\y in \clist{
\draw[very thin,gray] (\x cm,1pt) -- (\x cm,-1pt) node[anchor=north] {$\y$};
}
\end{tikzpicture}
\end{document}