![foreach 中的「間接」變數](https://rvso.com/image/298795/foreach%20%E4%B8%AD%E7%9A%84%E3%80%8C%E9%96%93%E6%8E%A5%E3%80%8D%E8%AE%8A%E6%95%B8.png)
我試圖繪製三個“圖形”,它們是並排放置的矩形。每個人都有四個點。這四點就是「分數」。
使用foreach
循環對於圖形來說是很自然的,因為所有佈局和標籤都是相同的。
我不明白的是如何將資料列表傳遞給每次迭代。在其他語言中,我會使用類似嵌套的東西foreach
,使用名稱指向要繪製的資料的間接變數來放置資料點。我似乎無法在 tikz 中找到變數間接。
目前,第二個 \foreach 似乎只看到一個值,而不是四個項目的清單。我可能使用了錯誤的方法。因此歡迎其他策略。
微量元素:
\documentclass[]{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\usetikzlibrary{calc}
\begin{document}
% Use A4 page shape.
% Base size of one graph is A4 page, but with pt instead of mm.
\begin{tikzpicture}
\pgfmathsetmacro{\scale}{1.75}
\pgfmathsetmacro{\graphHeight}{297 pt/\scale}
\pgfmathsetmacro{\graphWidth}{201 pt/\scale}
\def\labelsM{85, 10, 55, 75}
\def\labelsC{75, 20, 55, 65}
\def\labelsP{65, 30, 55, 55}
\def\graphInfo{ Graph one/{(-\graphWidth pt, 0pt)}/\labelsM,
Graph two/{(0pt, 0pt)}/\labelsC,
Graph three/{(\graphWidth pt, 0pt)}/\labelsP
}
\foreach \name/\pos/\values in \graphInfo
{
% Draw box
\node [
at = {\pos},
draw,
rectangle,
line width = 2pt,
minimum width = \graphWidth pt,
minimum height = \graphHeight pt,
fill = black!15,
name=\name
]
{} ;
% Name graph
\node [
font = \bfseries,
below = 2pt of \name.south
]
{\name} ;
% Vertical lines and labels (should be 4 equidistant vertical lines)
\foreach \s [count=\i] in \values {
\coordinate (top) at ($(\name.north west)!\i/5!(\name.north east)$) ;
\coordinate (bottom) at ($(\name.south west)!\i/5!(\name.south east)$) ;
\draw [dashed] (top) -- (bottom) ;
% Data to be plotted when this works
};
} % end foreach \name
\end{tikzpicture}
答案1
foreach 並沒有\values
完全擴展,只是深一層。所以它只看到\labelsM
而不是值。\values
使用前至少展開一次:
\expandafter\let\expandafter\values\values
\expandafter
展開下一個命令。所以第一個\expandafter
擴充第二個\expandafter
,第二個擴充第二個\values
,\labelsX
然後 TeX 繼續執行該\let
指令。最後你得到了\let\values\labelsX
。