如何在堆积条形图中切换行/列

如何在堆积条形图中切换行/列

这是我的 MWE:

\begin{tikzpicture}
\pgfplotstableread{ % Read the data into a table macro
Label   First   Second  Third
Yes      0.1     0.3     0.3
No      0.9     0.7     0.7
}\datatable

\begin{axis}[
    xbar stacked, % Stacked horizontal bars
    xmin=0, % Start x axis at 0
    ytick=data, % Use as many tick labels as y coordinates
    yticklabels from table={\datatable}{Label} % Get the labels from the Label column of the \datatable
]
\addplot [fill=yellow] table [x=First, y expr=\coordindex] {\datatable}; % Plot the "First" column against the data index
\addplot [fill=green!70!blue] table [x=Second, y expr=\coordindex] {\datatable};
\addplot [fill=red!80!yellow] table [x=Third, y expr=\coordindex] {\datatable};
\end{axis}
\end{tikzpicture}

此脚本生成一个图表,其中 y 轴对应于列的“是/否”值第一的第二, 和第三。如何更改脚本,使 y 轴对应于列(即第一的第二, 和第三)?我需要水平表示特定列的“是/否”分布。

答案1

我找到了解决方案转置表格并修改脚本如下:

\begin{tikzpicture}
\pgfplotstableread{ % Read the data into a table macro
Label First Second Third
Yes 0.1 0.3 0.3
No 0.9 0.7 0.7
}\datatable

\pgfplotstabletranspose[string type, colnames from=Label, input colnames to=Label]\datatabletransposed{\datatable}

\begin{axis}[
    xbar stacked, % Stacked horizontal bars
    xmin=0, % Start x axis at 0
    ytick=data, % Use as many tick labels as y coordinates
    yticklabels from table={\datatabletransposed}{Label} % Get the labels from the Label column of the \datatable
]
\addplot [fill=green!70!blue] table [x=Yes, y expr=\coordindex] {\datatabletransposed};
\addplot [fill=red!70!blue] table [x=No, y expr=\coordindex] {\datatabletransposed};
\end{axis}
\end{tikzpicture}

相关内容