我有一个条形图,我想设置 x 标签,但是当我这样做时,x 轴不合适:
\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
compat=newest, %Better label placement
legend style={at={(0.5,-0.15)},
anchor=north,legend columns=0},
xtick={1,2,3,4,5,6},
xticklabels={{$(3{,}2)$ EC},
{$2$-way rep},
{$(6{,}4)$ EC},
{$3$-way rep},
{$(12{,}8)$ EC},
{$5$-way rep}},
xtick=data,
enlargelimits=0.2,
nodes near coords,
axis lines*=left,
y axis line style={opacity=0},
yticklabels={\empty},
ytick style={draw=none},
ymin=0.0,
x tick label style={rotate=45},
ybar,
bar width=32,
width=1.2\textwidth,
]
\addplot+[ybar] plot coordinates {
(1, 1.5)
(2, 2)};
\addplot+[ybar] plot coordinates {
(3, 1.5)
(4, 3)};
\addplot+[ybar] plot coordinates {
(5, 1.5)
(6, 5) };
\addplot[red,sharp plot,update limits=false]
coordinates {(-3, 1) (9, 1)};
\legend{single protection, double protection, quadruple protection}
\end{axis}
\end{tikzpicture}
\end{document}
答案1
使用 时xtick=data
,PGFPlots 仅使用第一个命令的 x 坐标\addplot
来确定标签位置。您可以通过设置 来解决这个问题xtick={1,...,6}
。
为了获得条形的正确位置,您还应该设置bar shift=0pt
:
\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
compat=newest, %Better label placement
legend style={at={(0.5,-0.15)},
anchor=north,legend columns=0},
xtick={1,2,3,4,5,6},
xticklabels={{$(3{,}2)$ EC},
{$2$-way rep},
{$(6{,}4)$ EC},
{$3$-way rep},
{$(12{,}8)$ EC},
{$5$-way rep}},
nodes near coords,
axis lines*=left,
y axis line style={opacity=0},
yticklabels={\empty},
ytick style={draw=none},
ymin=0.0,
x tick label style={rotate=45},
ybar=0pt,
bar shift=0pt,
bar width=32,
width=1.2\textwidth,
]
\addplot+[ybar] plot coordinates {
(1, 1.5)
(2, 2)};
\addplot+[ybar] plot coordinates {
(3, 1.5)
(4, 3)};
\addplot+[ybar] plot coordinates {
(5, 1.5)
(6, 5) };
\addplot[red,sharp plot,update limits=false]
coordinates {(-3, 1) (9, 1)};
\legend{single protection, double protection, quadruple protection}
\end{axis}
\end{tikzpicture}
\end{document}