Re: \foreach e definizione di un colore dentro {axis}

#84826
Up
0
Down
::

egreg9″ post=84239Il problema principale è che [tt]\foreach[/tt] valuta ciascun passo in un gruppo. La definizione di [tt]randomcolor[/tt] potrebbe essere preceduta da [tt]\xglobal[/tt] (sezione 2.5.5 del manuale di xcolor). Ma non basterebbe, perché alla fine varrebbe solo l’ultimo. Il trucco è di definire un colore diverso per ciascuna iterazione: saranno [tt]randomcolor0[/tt] e così via.

Ecco qui, ho anche modificato un po’ le definizioni con [tt]\expandafter[/tt] rendendole un po’ più agili.
`% !TeX TS-program = LuaLaTeX

\documentclass[a4paper,10pt]{article}

\usepackage{amsmath}
\usepackage{pgfplots,pgfplotstable}
\usetikzlibrary{shapes.geometric,calc,intersections}
\pgfplotsset{compat=1.7}
\pgfplotstableset{format=inline, row sep=crcr}

\newcommand*\measurement[2]{%
\begingroup\edef\next{\endgroup
\unexpanded{\pgfplotstableread{#2}}%
{\unexpanded\expandafter{\csname measurements#1\endcsname}}}\next
}

\begin{document}

\measurement{0}{
0 0 \\
1 397 \\
2 3415 \\
3 3629 \\
4 3811 \\
}
\measurement{1}{
0 0 \\
1 365 \\
2 884 \\
3 1341 \\
4 1768 \\
}
\measurement{2}{
0 0 \\
1 1555 \\
2 2195 \\
3 2561 \\
4 2653 \\
}

\begin{figure}
\centering
\tracingassigns=1
\definecolor{mycol}{RGB}{1,1,1}
\tracingassigns=0
\begin{tikzpicture}
\begin{axis}[
xlabel={Packet ID},
ylabel={Cumulative dispersion ($\mu s$)},
xmin=0, ymin=0, xmax=4, ymax=4000
]
\foreach \x in {0,1,…,2} {
\edef\R{\pdfuniformdeviate 255}
\edef\G{\pdfuniformdeviate 255}
\edef\B{\pdfuniformdeviate 255}
\xglobal\definecolor{randomcolor\x}{RGB}{\R,\G,\B}
\begingroup\edef\next{\endgroup
\noexpand\addplot [draw=randomcolor\x] table from %
\unexpanded\expandafter{\csname measurements\x\endcsname};
}\next
}
\end{axis}
\end{tikzpicture}
\end{figure}

\end{document}`
Il trucco con [tt]\begingroup[/tt] e [tt]\endgroup[/tt] serve per rimuovere la definizione di [tt]\next[/tt] dalla memoria.

Ciao
Enrico

Ciao Enrico! Grazie mille.

I [tt]\begingroup[/tt]/[tt]\endgroup[/tt] dimentico sempre di metterceli… 🙂

In effetti non vedo perché fare `\noexpand\pgfplotstableread{\unexpanded{#2}}` quando conviene: `\unexpanded{\pgfplotstableread{#2}}`

Non mi è chiaro invece perché sia meglio `{\unexpanded\expandafter{\csname measurements#1\endcsname}}` anziché `{\expandafter\noexpand\csname measurements#1\endcsname}`
Potresti cortesemente spiegarmelo?

Nuovamente grazie!

Go to top