我想要另一组硬编码标签,它们位于每个条形图顶部,靠近底部(0)。即,像标签一样nodes near coords
,但向下移动到 0 处并使用我自己的自定义文本。因此,在下面的示例中,将有另外四个标签(未显示)。有没有简单的方法可以做到这一点?谢谢!
梅威瑟:
\documentclass[border=10pt]{standalone}
\usepackage{tikz}
\usepackage{pgfplotstable}
\renewcommand*{\familydefault}{\sfdefault}
\usepackage{sfmath}
\pgfplotsset{compat=1.12}
\pgfplotsset{
width=\textwidth,
}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ybar,axis on top, ymax=100,
ymin=30,
height=8cm,
width=5cm,
enlarge x limits=0.5,
ymajorgrids, tick align=inside,
major grid style={draw=white},
axis x line*=left,
ylabel={\%},
xtick=data,
legend cell align=left,
max space between ticks=20pt,
legend style={ at={(0.57,1.05)} ,
column sep=1ex },
symbolic x coords={label1, label2},
nodes near coords=\rotatebox{90}{\scriptsize\pgfmathprintnumber\pgfplotspointmeta},
]
\addplot[draw=none,fill=blue!40!white] coordinates {(label1,80.2) (label2,90.7) };
\addplot[draw=none,fill=red!40!white] coordinates {(label1,70) (label2,80) };
\legend{Data1, Data2}
\end{axis}
\end{tikzpicture}
\end{document}
答案1
以下适用于两个数据系列。想法是在每个 x 值下方添加两个标签,一个在左侧(anchor=east
),一个在右侧(anchor=west
)。x 位置取自系统symbolic x coordinates
,y 坐标取自xticklabel cs
位于 x 轴上的 。如果我们只是将相应的\node
命令放入轴环境中,它将被剪掉。该选项\after end axis/.code
允许指定在剪掉后要执行的代码。
\begin{tikzpicture}
\begin{axis}[
ybar,axis on top, ymax=100,
ymin=30,
height=8cm,
width=5cm,
enlarge x limits=0.5,
ymajorgrids, tick align=inside,
major grid style={draw=white},
axis x line*=left,
ylabel={\%},
xtick=data,
legend cell align=left,
max space between ticks=20pt,
legend style={ at={(0.57,1.05)} ,
column sep=1ex },
symbolic x coords={label1, label2},
nodes near coords=\rotatebox{90}{\scriptsize\pgfmathprintnumber\pgfplotspointmeta},
after end axis/.code={
\node(L1) at (axis cs:label1,1) {};
\node(L2) at (axis cs:label2,1) {};
\node(XTL) at (xticklabel cs:0) {};
\node[anchor=north east] at (L1 |- XTL) {L11};
\node[anchor=north west] at (L1 |- XTL) {L12};
\node[anchor=north east] at (L2 |- XTL) {L21};
\node[anchor=north west] at (L2 |- XTL) {L22};
},
]
\addplot[draw=none,fill=blue!40!white] coordinates {(label1,80.2) (label2,90.7) };
\addplot[draw=none,fill=red!40!white] coordinates {(label1,70) (label2,80) };
\legend{Data1, Data2}
\end{axis}
\end{tikzpicture}
编辑:x 轴上方的标签
我多读了,你希望将标签放在 xaxis 上方。这可以通过对上述代码进行以下更改来实现:
after end axis/.code={
\node(L1) at (axis cs:label1,1) {};
\node(L2) at (axis cs:label2,1) {};
\node(XTL) at (xticklabel* cs:0) {};
\node[anchor=south east] at (L1 |- XTL) {\rotatebox{90}{\scriptsize L11}};
\node[anchor=south west] at (L1 |- XTL) {\rotatebox{90}{\scriptsize L12}};
\node[anchor=south east] at (L2 |- XTL) {\rotatebox{90}{\scriptsize L21}};
\node[anchor=south west] at (L2 |- XTL) {\rotatebox{90}{\scriptsize L22}};
},