我正在尝试使用 pgfplots 制作条形图。我希望标签绘制在条形图内,除非空间不足。在这种情况下,标签应显示在条形图旁边。
我添加了一些代码来重现我正在制作的图表。如果百分比低于 3%,则没有足够的空间将节点左对齐。对于这些节点,我希望它右对齐。数据文件 data.dat 将从 latex 外部生成,并且数据值将来可能会有所不同,因此我正在寻找一个通用解决方案。任何帮助都将不胜感激。
\documentclass[a4paper, 9pt]{report}
\usepackage{filecontents}
\usepackage{pgfplots, pgfplotstable}
\begin{document}
\begin{filecontents}{data.dat}
rownum value value2 label
1 10 1.1 Cluster~A
2 14 6 Cluster~B
3 17 7 Cluster~C
4 15 2.2 Cluster~D
5 19 4 Cluster~E
6 18 11 Cluster~F
\end{filecontents}
\begin{figure}[h]
\caption{A caption.}
\begin{tikzpicture}
\begin{axis}[
xbar,
y dir=reverse,
axis y line*=none,
axis x line*=none,
major tick length=0,
xmin=0,
xmax=50,
enlarge x limits={abs=0.00005},
scale only axis, width=10cm,
ytick={1,...,6},
xtick={0, 10, ..., 50},
xticklabel=\pgfmathprintnumber{\tick}\,\%,
yticklabel style={text width=3cm, align=right},
yticklabels from table={data.dat}{label},
xmajorgrids,
major grid style={black},
tick style={black},
bar width=4mm,
y=12mm,
enlarge y limits={abs=0.6},
nodes near coords={\pgfmathprintnumber[precision=0]\pgfplotspointmeta\%},
nodes near coords align=left
]
\addplot [draw=lime , fill=lime] table [x=value, y=rownum] {data.dat};
\addplot [draw=orange , fill=orange] table [x=value2, y=rownum] {data.dat};
\end{axis}
\end{tikzpicture}
\end{figure}
\end{document}
答案1
您可以使用键检查值是否小于 3 visualization depends on={meta < 3 \as \valueissmall}
,然后使用比较的结果设置标签的锚点(请注意使用以及值后的\ifdim
需要):pt
every node near coord/.append style={
anchor={\ifdim\valueissmall pt=1 pt west\else east\fi}
}
\documentclass[a4paper, 9pt]{report}
\usepackage{filecontents}
\usepackage{pgfplots, pgfplotstable}
\begin{document}
\begin{filecontents}{data.dat}
rownum value value2 label
1 10 1.1 Cluster~A
2 14 6 Cluster~B
3 17 7 Cluster~C
4 15 2.2 Cluster~D
5 19 4 Cluster~E
6 18 11 Cluster~F
\end{filecontents}
\begin{figure}[h]
\caption{A caption.}
\begin{tikzpicture}
\begin{axis}[
xbar,
y dir=reverse,
axis y line*=none,
axis x line*=none,
major tick length=0,
xmin=0,
xmax=50,
enlarge x limits={abs=0.00005},
scale only axis, width=10cm,
ytick={1,...,6},
xtick={0, 10, ..., 50},
xticklabel=\pgfmathprintnumber{\tick}\,\%,
yticklabel style={text width=3cm, align=right},
yticklabels from table={data.dat}{label},
xmajorgrids,
major grid style={black},
tick style={black},
bar width=4mm,
y=12mm,
enlarge y limits={abs=0.6},
nodes near coords={\pgfmathprintnumber[precision=0]\pgfplotspointmeta\%},
visualization depends on={meta < 3 \as \valueissmall},
every node near coord/.append style={
anchor={\ifdim\valueissmall pt=1 pt west\else east\fi}
}
]
\addplot [draw=lime , fill=lime] table [x=value, y=rownum] {data.dat};
\addplot [draw=orange , fill=orange] table [x=value2, y=rownum] {data.dat};
\end{axis}
\end{tikzpicture}
\end{figure}
\end{document}