我之前问过一个问题如何将数据标签放在条形图中的文本标签旁边?。虽然提供的解决方案适用于该示例中的特定输入数据值,但当我尝试使用该解决方案适应不同的输入数据值时,却出现了错误。
当我尝试编译以下代码时:
\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ytick={1,2,3},
yticklabels={Optimized Prices,Current Prices,
No Promotions},
xbar,
xlabel=Profit,
nodes near coords, nodes near coords align={horizontal},
% begin new bit
visualization depends on=x \as \rawx,
every node near coord/.append style={
shift={(axis direction cs:-\rawx+0.8,0)}}
% end new bit
]
\addplot table {
x y
1000 3
1100 2
1200 1
};
\end{axis}
\end{tikzpicture}
\end{document}
我得到了错误
! Package PGF Math Error: Could not parse input '-1000.0000000+0.8' as a floati
ng point number, sorry. The unreadable part was near '+0.8'..
See the PGF Math package documentation for explanation.
Type H <return> for immediate help.
...
l.26 \end{axis}
如果我删除+0.8
,并编译以下代码:
\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ytick={1,2,3},
yticklabels={Optimized Prices,Current Prices,
No Promotions},
xbar,
xlabel=Profit,
nodes near coords, nodes near coords align={horizontal},
% begin new bit
visualization depends on=x \as \rawx,
every node near coord/.append style={
shift={(axis direction cs:-\rawx,0)}}
% end new bit
]
\addplot table {
x y
1000 3
1100 2
1200 1
};
\end{axis}
\end{tikzpicture}
\end{document}
我得到以下输出:
上面的代码有什么问题?我知道我将文本标签移动了错误的长度,但是我该如何指定正确的长度呢?
答案1
执行此操作时,shift={(axis direction cs:-\rawx,0)}
您将节点移至x = 0
。但是,在您的例子中,轴从 开始x = 980
,因此节点最终位于轴左侧 980 个轴单位处。您需要执行的移位是xmin - \rawx
,这将是单个 的长度xbar
。您可以xmin
使用访问\pgfkeysvalueof{/pgfplots/xmin}
,因此所需的shift
是
shift={(axis direction cs:\pgfkeysvalueof{/pgfplots/xmin}-\rawx,0)}}
(第一栏太短,容纳不下文本,例如,您可以将xmin=900
其设置得稍微长一些。)
\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ytick={1,2,3},
yticklabels={Optimized Prices,Current Prices,
No Promotions},
xbar,
xlabel=Profit,
nodes near coords, nodes near coords align={horizontal},
% begin new bit
visualization depends on=x \as \rawx,
every node near coord/.append style={
font=\tiny,
shift={(axis direction cs:\pgfkeysvalueof{/pgfplots/xmin}-\rawx,0)}}
% end new bit
]
\addplot table {
x y
1000 3
1100 2
1200 1
};
\end{axis}
\end{tikzpicture}
\end{document}