You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整TikZ条形图的Y轴标签使其与条形对齐?

TikZ条形图Y轴标签与条形对齐问题解决

我在用TikZ绘制条形图时遇到了Y轴标签和条形未对齐的问题。修改自一个条形图示例,添加了若干数据字段并移除了第二个分类,代码如下:

\documentclass[border=10pt]{standalone}
usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}

\begin{tikzpicture}
  \begin{axis}[title  = Contributions per category
                          at LaTeX-Community.org,
    xbar,
    y axis line style = { opacity = 0 },
    axis x line       = none,
    tickwidth         = 0pt,
    enlarge y limits  = 0.2,
    enlarge x limits  = 0.02,
    symbolic y coords = {test1,test2,test3,test4,LaTeX, Tools, Distributions, Editors},
    nodes near coords,
  ]
  \addplot coordinates { (57727,LaTeX)         (5672,Tools)
                         (2193,Distributions)  (11106,Editors)
                         (11106,test1)
                         (11106,test2)
                         (11106,test3)
                         (11106,test4)
                         };

  \legend{Topics}
  \end{axis}
\end{tikzpicture}

\end{document}

问题原因与解决方法

问题核心是**symbolic y coords的定义顺序和\addplot中坐标的Y值顺序不匹配**。在xbar类型的图中,symbolic y coords的列表是按从下到上的顺序排列Y轴标签的,而你的坐标列表里的Y值顺序混乱,导致标签和对应条形错位。另外代码里还存在语法错误:usepackage{pgfplots}漏写了开头的反斜杠\。

修正后的完整代码

\documentclass[border=10pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}

\begin{tikzpicture}
  \begin{axis}[title  = Contributions per category
                          at LaTeX-Community.org,
    xbar,
    y axis line style = { opacity = 0 },
    axis x line       = none,
    tickwidth         = 0pt,
    enlarge y limits  = 0.2,
    enlarge x limits  = 0.02,
    symbolic y coords = {test1,test2,test3,test4,LaTeX,Tools,Distributions,Editors},
    nodes near coords,
  ]
  \addplot coordinates { 
    (11106,test1)
    (11106,test2)
    (11106,test3)
    (11106,test4)
    (57727,LaTeX)         
    (5672,Tools)
    (2193,Distributions)  
    (11106,Editors)
  };

  \legend{Topics}
  \end{axis}
\end{tikzpicture}

\end{document}

说明

  1. 调整symbolic y coords的顺序,让它和\addplot中坐标的Y值顺序完全对应,确保每个标签匹配正确的条形位置;
  2. 补全usepackage开头的\,修正语法错误;
  3. 重新整理坐标列表排版,顺序更清晰,便于后续维护。

内容的提问来源于stack exchange,提问作者Ximi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 18:01:16