我想将一组条形图(例如下面 MWE 中的子集)转换为更清晰的堆积条形图,如下例所示:
\documentclass{article}
\usepackage{tikz}
\begin{document}
Calendars and reminders\\
\begin{centering}
\begin{bchart}[max=70,scale=1,width=14cm,unit=\%]
\bcbar[text={Daily},color=cyan!20!green!40]{51}
\bcbar[text={Weekly},color=cyan!60!green!20]{24}
\bcbar[text={Less often}, color=cyan!10]{25}
\end{bchart}
\end{centering}
Send/receive texts\\
\begin{centering}
\begin{bchart}[max=70,scale=1,width=14cm,unit=\%]
\bcbar[text={Daily},color=cyan!20!green!40]{67}
\bcbar[text={Weekly},color=cyan!60!green!20]{23}
\bcbar[text={Less oft}, color=cyan!10]{7}
\end{bchart}
\end{centering}
Make or receive phone calls\\
\begin{centering}
\begin{bchart}[max=70,scale=1,width=14cm,unit=\%]
\bcbar[text={Daily},color=cyan!20!green!40]{46}
\bcbar[text={Weekly},color=cyan!60!green!20]{38}
\bcbar[text={Less often}, color=cyan!10]{16}
\end{bchart}
\end{centering}
\end{document}
我尝试使用此处之前提出的问题的解决方案(如何使用 tikz 绘制条形图?) 没有成功。
你能帮忙吗?谢谢!
我的第一次尝试(不是 MWE,但让你知道我做错了什么):
\begin{tikzpicture}
\pgfplotstableread{ % Read the data into a table macro
Label Daily Weekly Less~often
Calendars~and~reminders 0.51 0.24 0.25
Send/receive~texts 0.67 0.23 0.07
Make/receive~phone~calls 0.46 0.38 0.16
}\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=cyan!20!green!40] table [x=First, y expr=\coordindex] {\datatable}; % "First" column against the data index
\addplot [fill=cyan!60!green!20]table [x=Second, y expr=\coordindex] {\datatable};
\addplot [fill=cyan!10] table [x=Third, y expr=\coordindex] {\datatable};
\end{axis}
\end{tikzpicture}
答案1
基于 OP 的 MWE,这是使其工作的尝试,以便 OP 可以有一个起点。主要错误来自Label 列中的(现在被 \space 替换)以及读入时~
使用(现在它们已更改为 Daily、Weekly 和 LessOften)。x=First, Second and Third
代码
\documentclass[border=10pt]{standalone}%[a4paper]{article}
\usepackage{tikz,pgfplots,pgfplotstable}
\pgfplotsset{compat=1.8}
\begin{document}
\pgfplotstableread{ % Read the data into a table macro
Label Daily Weekly LessOften
Calendars\space And\space Reminders 0.51 0.24 0.25
Send/receive\space Texts 0.67 0.23 0.07
Make/receive\space Phone\space Calls 0.46 0.38 0.16
}\testdata
\begin{tikzpicture}
\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={\testdata}{Label} % Get the labels from the Label column of the \datatable
]
\addplot [fill=cyan!20!green!40] table [x=Daily, meta=Label,y expr=\coordindex] {\testdata}; % "First" column against the data index
\addplot [fill=cyan!60!green!20] table [x=Weekly, meta=Label,y expr=\coordindex] {\testdata};
\addplot [fill=cyan!10] table [x=LessOften, meta=Label,y expr=\coordindex] {\testdata};
\end{axis}
\end{tikzpicture}
\end{document}