条形图/图形,节点为实际值和百分比

条形图/图形,节点为实际值和百分比

我希望每个条的节点都是实际值及其对应的百分比。

以下是我所拥有的:

\begin{figure}[h]
    \centering
\begin{tikzpicture}
                \tikzstyle{every node}=[font=\scriptsize]
                \begin{axis}[
                axis lines*=left,
                title=myTitle,
                xbar, 
                xmin=0,
                xmax=50,
                width=9cm,
                height=5cm,
                enlarge y limits=0.3,
                xlabel={Number of Stuff},
                symbolic y coords={A, B, C},
                ytick=data,
                nodes near coords,
                point meta={x*100/44},
                nodes near coords={(\pgfmathprintnumber\pgfplotspointmeta\%)},
                nodes near coords align={horizontal},
                y tick label style={font=\scriptsize,text width=1.2cm,align=center}
                ]
                \addplot coordinates{(42,C) (40,B) (32,A)};
                \end{axis}
\end{tikzpicture}
    \caption{A test}
    \label{hist:auth}
\end{figure}

得出以下结论: 韋結果

因此,我希望在 A 的栏旁边有以下节点:32 (73%)

我一直在玩nodes near coords={(\pgfmathprintnumber\pgfplotspointmeta\%)}但却没能弄明白。

答案1

原始数据的存储方式rawx\tikzstyle已被弃用。

\documentclass[tikz]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\begin{document}
\begin{tikzpicture}[every node/.append style={font=\scriptsize}]
  \begin{axis}[visualization depends on=rawx \as \myx,
     axis lines*=left,
     title=myTitle,
     xbar, 
     xmin=0,
     xmax=50,
     width=9cm,
     height=5cm,
     enlarge y limits=0.3,
     xlabel={Number of Stuff},
     symbolic y coords={A, B, C},
     ytick=data,
     nodes near coords,
     point meta={x*100/44},
     nodes near coords={\pgfmathprintnumber\myx~(\pgfmathprintnumber\pgfplotspointmeta\%)},
     nodes near coords align={horizontal},
     y tick label style={font=\scriptsize,text width=1.2cm,align=center}
     ]
     \addplot coordinates{(42,C) (40,B) (32,A)};
  \end{axis}
\end{tikzpicture}
\end{document}

在此处输入图片描述

答案2

这是使用纯 TikZ 的方法

\documentclass[tikz,border=3mm]{standalone}
\begin{document}
\begin{tikzpicture}[x=1.5cm]
\pgfkeys{/pgf/number format/.cd,fixed,precision=2}

\foreach \i in {0,1,...,5}{
\pgfmathsetmacro{\num}{int(10*\i)}  
\draw (\i,0) node[below=1mm]{$\num$}--+(90:2mm);
}
% Total 44 participants
\foreach \j/\jtext/\jnum in {1/A/32,2/B/40,3/C/42}{
\draw (0,\j) node[left=5mm]{\jtext}--+(180:2mm);
\pgfmathsetmacro{\jpercent}{\jnum/44*100};       
\draw[blue!50,line width=3mm] (0,\j)--+(0:\jnum/10) 
node[right,blue]{$\jnum \;(\pgfmathprintnumber{\jpercent} \%)$};
}

\draw (0,3.5)--(0,0)--(5,0);
\path
(current bounding box.north) node[above]{My title}
(current bounding box.south) node[below=2mm]{Number of Participants};
\end{tikzpicture}
\end{document}

在此处输入图片描述

相关内容