在 PGFplotstable 中使用巨集結果與巨集擴展

在 PGFplotstable 中使用巨集結果與巨集擴展

我有以下 MWE:

\documentclass{article}
\usepackage{pgfplotstable}
\usepackage{ifthen}

\newcommand*{\rightOutput}{%
    \pgfplotstableread[col sep = comma]{rawcutoffs.csv}\rawdata

    \pgfplotstabletypeset[%
        columns/LetterGrade/.style={string type,column type = l},
        columns/Average/.style={column type = r},
    ]{\rawdata}
}

\def\paramOutput#1{%
    \pgfplotstableread[col sep = comma]{rawcutoffs.csv}\rawdata

    \pgfplotstabletypeset[%
    #1
    ]{\rawdata}
}

\newcommand*{\parser}[1]{%
    \foreach \x/\y in {#1} {%
        \ifthenelse{\equal{n}{\x}}{columns/\y/.style={column type = r},}{columns/\y/.style={string type,column type = l},}%
    }%
}

\def\straighttext{%
    columns/LetterGrade/.style={string type,column type = l},
    columns/Average/.style={column type = r},
}

\begin{document}
%This macro is ultimately what I desire, and it works
\rightOutput

%This macro works, but it is not what I desire
\expandafter\paramOutput\expandafter{\straighttext}

%This macro doesn't work at all - WHY?
%\expandafter\paramOutput\expandafter{\parser{s/LetterGrade,n/Average}}
\end{document}

CSV 檔案 rawcutoffs.csv 如下所示:

LetterGrade,Average
A,90
B,80
C,70

當我嘗試使用命令解析器時,它不會將解析器的結果提供給 paramOutput 命令 - 相反,它將程式碼本身提供給 paramOutput。我很好奇是否有辦法取得命令解析器的結果作為 paramOutput 的參數?當我使用命令 Straighttext 時,它會給出我想要的輸出。

答案1

問題在於,在將輸出\parser賦予 之前,需要對其進行擴展\pgfplotstabletypeset。為了解決這個問題,我認為最簡單的方法是建立一個字串,如下所示\specs,其中包含 的“輸出” \parser,然後您可以使用類似的方法強制擴展該字串

 \xdef\myplot{\noexpand\pgfplotstabletypeset[\specs]}

下面我使用\specs\xappto來自電子工具箱- 它用於將內容附加到\specs.我還將\parser程式碼移入其中\paramOutput\paramOutput接受逗號分隔的規範清單。它不需要以這種方式完成,但自從\paramOutput現在建造以來,它對我來說似乎更自然\specs。我還用於\ifx字串比較( to\xns,這需要額外的\expandafter強制\x擴展(出於某種原因我傾向於避免\ifthenelse...)。

透過這些更改,您的 MWE 將變為:

\documentclass{article}
\usepackage{pgfplotstable}
\usepackage{pgffor}
\usepackage{etoolbox}

\newcommand*{\rightOutput}{%
    \pgfplotstableread[col sep = comma]{rawcutoffs.csv}\rawdata%
    %
    \pgfplotstabletypeset[%
        columns/LetterGrade/.style={string type,column type = l},
        columns/Average/.style={column type = r},
    ]{\rawdata}
}

\def\paramOutput#1{%
    \pgfplotstableread[col sep = comma]{rawcutoffs.csv}\rawdata%
    \def\specs{}%
    \foreach \x/\y in {#1} {
      \expandafter\ifx\x n\xappto\specs{columns/\y/.style={column type = r},}%
      \else\xappto\specs{columns/\y/.style={string type,column type = l},}%
      \fi
    }%
    \xdef\myplot{\noexpand\pgfplotstabletypeset[\specs]}%
    \myplot{\rawdata}%
}

\begin{document}
    %This macro is ultimately what I desire, and it works
    \rightOutput

    %This macro now works!
    \paramOutput{s/LetterGrade,n/Average}
\end{document}

這給出了我認為所需的輸出:

在此輸入影像描述

相關內容