我有一个图形,其中一个标签很长。我想将此标签拆分为两行。目前我的代码如下
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.10}
\begin{document}
\begin{tikzpicture}
\pgfplotsset{width=10 cm}
\begin{axis} [
symbolic x coords={0, Label 1, Label 2, This is a very very very long label, Label 4, Label 5, Label 6, Label 7,Label 8},
xtick={Label 1, Label 2, This is a very very very long label, Label 4, Label 5, Label 6, Label 7},
x tick label style={rotate=45, anchor=east, align=center},
axis lines*=left,
ymajorgrids = true,
legend style={at={(0.5,-0.30)},anchor=north},
ymin=0,
ymax=175,
bar width=5mm,
ybar=-0.5cm,
enlarge x limits={abs=0.6cm},
nodes near coords,
every node near coord/.append style={color=black},
]
\addplot [red,fill=red]
coordinates{ (Label 1,100) (Label 2,90) (This is a very very very long label,80) (Label 4,140) } ;
\addplot [blue,fill=blue]
coordinates{ (Label 5,80) (Label 6,25) (Label 7,66) } ;
\addlegendentry{Legend 1}
\addlegendentry{Legend 2}
\end{axis}
\end{tikzpicture}
\end{document}
由此产生了如下结果:
现在,如果我尝试将 x 刻度标签样式更改为
x tick label style={rotate=45, anchor=east, align=center,text width=3.5cm}
有时候是这样的:
因此,anchor=east 命令似乎与文本宽度命令不兼容。其他锚点命令(如 anchor=west、anchor=base)似乎运行正常。有人知道为什么 anchor east 命令似乎与文本宽度命令不兼容吗?有没有办法解决这个问题?
答案1
您的x tick label
s 锚定在东边。但由于您给出了align=center
和 ,textwidth=3.5cm
较短的标签将与中心对齐,右侧留有空白。因此它们与 x 轴保持一定距离。要解决此问题,请将它们与 对齐到align=right
右侧
x tick label style={rotate=45, anchor=east, align=right,text width=3.5cm},
完整代码:
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.10}
\begin{document}
\begin{tikzpicture}
\pgfplotsset{width=10 cm}
\begin{axis} [
symbolic x coords={0, Label 1, Label 2, This is a very very very long label, Label 4, Label 5, Label 6, Label 7,Label 8},
xtick={Label 1, Label 2, This is a very very very long label, Label 4, Label 5, Label 6, Label 7},
x tick label style={rotate=45, anchor=east, align=right,text width=3.5cm},
axis lines*=left,
ymajorgrids = true,
legend style={at={(0.5,-0.30)},anchor=north},
ymin=0,
ymax=175,
bar width=5mm,
ybar=-0.5cm,
enlarge x limits={abs=0.6cm},
nodes near coords,
every node near coord/.append style={color=black},
]
\addplot [red,fill=red]
coordinates{ (Label 1,100) (Label 2,90) (This is a very very very long label,80) (Label 4,140) } ;
\addplot [blue,fill=blue]
coordinates{ (Label 5,80) (Label 6,25) (Label 7,66) } ;
\addlegendentry{Legend 1}
\addlegendentry{Legend 2}
\end{axis}
\end{tikzpicture}
\end{document}