I'm trying to finalize my first pgfplots
chart. I've managed to get is almost the way I would like it to be with thanks to all examples I found here.
The last thing I can't seem to figure out is how to prevent plotting of value labels below 4% as they don't fit the bar (and small percentages aren't really relevant in this specific case).
I've found an example here on how to suppress the text from showing when the value is 0. I feel that it's just a small step to getting it to work. What I tried was to use \pgfmathfloatifflags
and test for negative numbers on \pgfplotspointmeta
minus 4. Would this work? I've not gotten it to work. I believe my understanding of the semantics of TeX/PGF is not adequate.
The result so far:
I tried to post an image here but as a new user I'm not allowed. Let me describe the issue: One data point has value 2. The bar segment of this data point is too small for the value to be plotted inside bar segment. It's overlapping now with another value. I would like small values to not be plotted in the chart.
The code I'm currently using is:
\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\begin{document}
\pgfplotstableread{
y x1 x2 x3 ylabel
1 41 4 55 {Unit A}
2 60 2 38 {Unit B}
3 20 50 30 {Unit C}
4 0 20 80 {Unit D}
}\datatable
\begin{figure}
\caption{How to not show labels $<4\%$}
\centering
\begin{tikzpicture}
\begin{axis}[
xbar stacked,
legend style={
legend columns=3,
at={(xticklabel cs:0.5)},
anchor=north,
draw=none
},
ytick=data,
axis y line*=left,
axis x line*=bottom,
tick label style={font=\footnotesize},
legend style={font=\footnotesize},
label style={font=\footnotesize},
xtick={0,20,40,60,80,100},
width=\textwidth,
bar width=6mm,
yticklabel style={text width=3cm, align=right},
yticklabels from table={\datatable}{ylabel},
xmin=0,
xmax=100.1,
y=8mm,
enlarge y limits={abs=0.7},
point meta=explicit,
every node near coord/.style={
check for zero/.code={
\pgfmathfloatifflags{\pgfplotspointmeta}{0}{
\pgfkeys{/tikz/coordinate}
}{}
}, check for zero, xshift=3, font=\scriptsize},
nodes near coords={\pgfmathprintnumber[fixed zerofill,precision=0]{\pgfplotspointmeta}$\%$},
nodes near coords align=left
]
\addplot table [x=x1, y=y, meta=x1] \datatable;
\addplot table [x=x2, y=y, meta=x2] \datatable;
\addplot table [x=x3, y=y, meta=x3] \datatable;
\legend{lorem,ipsum, dolor}
\end{axis}
\end{tikzpicture}
\label{fig:test}
\end{figure}
\end{document}
Best Answer
Almost there! You only need to perform the subtraction in an extra step before doing the comparison, you can't put it right in the
\pgfmathfloatifflags
command.Since the value of
\pgfplotspointmeta
is in floating point notation, you'll first have to switch on thefpu
(thefloating point unit
) library using\pgfkeys{/pgf/fpu=true}
, then perform the subtraction using\pgfmathparse{\pgfplotspointmeta-4}
, check if the result is negative using\pgfmathfloatifflags{\pgfmathresult}{-}
, and finally switch off thefpu
library again.