使用以下代码生成的条形图的 y 轴不是从 0 开始,也不是以 100 结束。而是从我的数字的最小值到最大值显示。我如何将其更改为显示从 0 到 100 的比例?
\begin{tikzpicture}
\begin{axis}[
ybar,
enlargelimits=0.10,
legend style={at={(0.5,-0.15)},
anchor=north,legend columns=-1},
symbolic x coords={Test1,Test2,Test3,Test4},
xtick=data,
nodes near coords,
nodes near coords align={vertical},
]
\addplot coordinates {(Test1,40) (Test2,60) (Test3,30.1) (Test4,88.2)};
\addplot coordinates {(Test1,70) (Test2,89.1) (Test3,42.3) (Test4,71.2)};
\legend{Test one,Test two}
\end{axis}
\end{tikzpicture}
答案1
通常情况下,您只需要添加ymax=100
到axis
选项中,但是因为您还需要通过将 更改为来enlargelimits
禁用 y 轴。enlargelimits
enlarge x limits
有多种策略可以避免数字和相邻条形图重叠,下面的代码说明了其中三种:
bar shift=<length>
通过在每个条形图上添加来增大条形图之间的空间\addplot
。增加条形的宽度。
减小数字的字体大小。
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.14}
\begin{document}
%Increase the space between bars, by adding a bar shift to each addplot:
\begin{tikzpicture}
\begin{axis}[
ybar,ymax=100,
enlarge x limits=0.15,
legend style={at={(0.5,-0.15)},
anchor=north,legend columns=-1},
symbolic x coords={Test1,Test2,Test3,Test4},
xtick=data,
nodes near coords,
nodes near coords align={vertical},
]
\addplot +[bar shift=8pt] coordinates {(Test1,40) (Test2,60) (Test3,30.1) (Test4,88.2)};
\addplot +[bar shift=-8pt] coordinates {(Test1,70) (Test2,89.1) (Test3,42.3) (Test4,71.2)};
\legend{Test one,Test two}
\end{axis}
\end{tikzpicture}
%Make the bars wider:
\begin{tikzpicture}
\begin{axis}[
ybar,ymax=100,
enlarge x limits=0.2, % modified
bar width=18pt, %%% <-------- added
legend style={at={(0.5,-0.15)},
anchor=north,legend columns=-1},
symbolic x coords={Test1,Test2,Test3,Test4},
xtick=data,
nodes near coords,
nodes near coords align={vertical},
]
\addplot coordinates {(Test1,40) (Test2,60) (Test3,30.1) (Test4,88.2)};
\addplot coordinates {(Test1,70) (Test2,89.1) (Test3,42.3) (Test4,71.2)};
\legend{Test one,Test two}
\end{axis}
\end{tikzpicture}
%Reduce the font size of the numbers:
\begin{tikzpicture}
\begin{axis}[
ybar,ymax=100,
enlarge x limits=0.2,
legend style={at={(0.5,-0.15)},
anchor=north,legend columns=-1},
symbolic x coords={Test1,Test2,Test3,Test4},
xtick=data,
nodes near coords,
nodes near coords align={vertical},
every node near coord/.append style={font=\tiny}%%% <-------- added
]
\addplot coordinates {(Test1,40) (Test2,60) (Test3,30.1) (Test4,88.2)};
\addplot coordinates {(Test1,70) (Test2,89.1) (Test3,42.3) (Test4,71.2)};
\legend{Test one,Test two}
\end{axis}
\end{tikzpicture}
\end{document}