我正在pgfplot
使用选项创建一个带有垂直条的图表xbar
。该图在 y 轴上有四个值,每个 y 轴刻度有三个条。
我如何控制空间量:
- 添加到第一个栏上方(例如 AnotherOne)
- 在最后一栏下方添加(例如 FooBar)
- 各组钢筋之间
我知道,y=<some value>
但这只适用于(3),使用它我需要硬编码一个特定的值,此外,对于每组只有一个条形图的图,我可以轻松计算加上bar width
一些填充,但是当每组有三个条形图时似乎不起作用。
最小工作示例:
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}
\usetikzlibrary{patterns}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xbar,
xmin=0,
y=2cm,
width = 12cm,
%height = 9cm,
bar width=10pt,
xlabel={Percentage},
nodes near coords,
% nodes near coords align=below, % places labels inside bars
symbolic y coords={FooBar, FooBaz, OneMore, AnotherOne },
ytick = data,
enlarge x limits={value=0.5,upper},
legend pos=south east,
legend image post style={scale=2.1},
legend style={row sep=8pt, column sep=8pt}
]
\addplot[pattern=north west lines,pattern color=black] coordinates { (0,FooBar) (0,FooBaz) (60.0,OneMore) (40.0,AnotherOne) };
\addplot[fill=black] coordinates { (0,FooBar) (0,FooBaz) (84.5,OneMore) (15.5,AnotherOne) };
\addplot[pattern=crosshatch dots,pattern color=black] coordinates { (7,FooBar) (5,FooBaz) (62,OneMore) (18,AnotherOne) };
\legend{Group 1, Group 2, Group 3}
\end{axis}
\end{tikzpicture}
\end{document}
答案1
这是我的解决方案,感谢@Torbjørn 提出的最初想法:
梅威瑟:
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}
\usetikzlibrary{patterns}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xbar,
xmin=0,
width = 12cm,
% reduce height to 'squeeze' bars together
% and reduce the spacing between bars
height = 8cm,
bar width=10pt,
xlabel={Percentage},
nodes near coords,
symbolic y coords={FooBar, FooBaz, OneMore, AnotherOne },
ytick = data,
enlarge x limits={value=0.5,upper},
% using `auto` here not `upper` and/or `lower`
% increase value to add additional space above
% and below the bars!
enlarge y limits={value=0.2,auto},
legend pos=south east,
legend image post style={scale=2.1},
legend style={row sep=8pt, column sep=8pt}
]
\addplot[pattern=north west lines,pattern color=black] coordinates
{ (0,FooBar) (0,FooBaz) (60.0,OneMore) (40.0,AnotherOne) };
\addplot[fill=black] coordinates
{ (0,FooBar) (0,FooBaz) (84.5,OneMore) (15.5,AnotherOne) };
\addplot[pattern=crosshatch dots,pattern color=black] coordinates
{ (7,FooBar) (5,FooBaz) (62,OneMore) (18,AnotherOne) };
\legend{Group 1, Group 2, Group 3}
\end{axis}
\end{tikzpicture}
\end{document}