LaTeX图表图例异常显示为S,如何修复代码错误?
问题:PGFPlots图表图例异常,仅显示带“S”的方框
使用LaTeX的TikZ/PGFPlots绘制机器人存量趋势图时,本该显示在图表下方的图例未正常渲染,仅出现一个带有“S”的方框。代码及效果截图如下:
\begin{document} \begin{tikzpicture} \begin{axis}[ axis lines=center, width=16cm, height=8cm, xlabel={Year}, ylabel={Stock of Operational Robots in Major Countries 1994-2014}, xmin=1994, xmax=2014, ymin=0, ymax=450, xtick={1994,1996,1998,2000,2002,2004,2006,2008,2010,2012,2014,2015}, ytick={0,50,100,150,200,250,300,350,400}, xtick style={draw=none}, ytick style={draw=none}, ymajorgrids=true, grid style=dashed, ] \addplot[ color=blue, mark=square, ] table [col sep=comma,x=Year,y=China] {data.csv}; \addplot[ color=red, mark=triangle, ] table [col sep=comma,x=Year,y=Japan] {data.csv}; \addplot[ color=green, mark=diamond, ] table [col sep=comma,x=Year,y=US] {data.csv}; \addplot[ color=purple, mark=*, ] table [col sep=comma,x=Year,y=SouthKorea] {data.csv}; \addplot[ color=orange, mark=star, ] table [col sep=comma,x=Year,y=Germany] {data.csv}; % Legende \legend{China, Japan, US, South Korea, Germany} \legend style={ at={(0.5,-0.15)}, % unterhalb des Diagramms zentriert anchor=north, draw=none, % keine Linie um die Legende font=\footnotesize, % Schriftgröße der Legende anpassen /tikz/every even column/.append style={column sep=0.5cm}, % Abstand zwischen Einträgen in der Legende anpassen } \end{axis} \end{tikzpicture} \end{document}
图表效果截图:
问题排查
- 语法错误:
\legend style是错误写法,PGFPlots中轴环境的样式选项不需要前缀反斜杠,正确写法为legend style。 - 位置错误:图例样式配置应该作为
axis环境的选项之一,而非单独放在绘图命令之后,否则样式无法被正确应用到图例上。
修复后的完整代码
\begin{document} \begin{tikzpicture} \begin{axis}[ axis lines=center, width=16cm, height=8cm, xlabel={Year}, ylabel={Stock of Operational Robots in Major Countries 1994-2014}, xmin=1994, xmax=2014, ymin=0, ymax=450, xtick={1994,1996,1998,2000,2002,2004,2006,2008,2010,2012,2014,2015}, ytick={0,50,100,150,200,250,300,350,400}, xtick style={draw=none}, ytick style={draw=none}, ymajorgrids=true, grid style=dashed, % 将图例样式移至axis选项内,修正语法 legend style={ at={(0.5,-0.15)}, % 图表下方居中 anchor=north, draw=none, % 取消图例边框 font=\footnotesize, % 缩小图例字体 /tikz/every even column/.append style={column sep=0.5cm} % 调整图例项间距 } ] \addplot[color=blue, mark=square] table [col sep=comma,x=Year,y=China] {data.csv}; \addplot[color=red, mark=triangle] table [col sep=comma,x=Year,y=Japan] {data.csv}; \addplot[color=green, mark=diamond] table [col sep=comma,x=Year,y=US] {data.csv}; \addplot[color=purple, mark=*] table [col sep=comma,x=Year,y=SouthKorea] {data.csv}; \addplot[color=orange, mark=star] table [col sep=comma,x=Year,y=Germany] {data.csv}; \legend{China, Japan, US, South Korea, Germany} \end{axis} \end{tikzpicture} \end{document}
修复说明
- 将
legend style配置移至axis的选项列表中,修正了语法错误,确保样式规则被正确解析。 - 保留了原有的图例位置、字体大小、间距等配置,修复后图例将正常显示在图表下方居中位置,且每个图例项与对应曲线样式匹配。
内容的提问来源于stack exchange,提问作者geekgeekgeek
相关产品推荐
相关产品推荐

