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

如何在TikZ中绘制带对数Y轴的堆叠条形图?

解决TikZ堆叠条形图对数轴的问题

针对你遇到的对数轴堆叠条形图报错、间隙及信息展示问题,可通过以下修改后的代码解决:

修改后的完整代码

\documentclass[preprint,12pt, 3p, sort&compress]{elsarticle}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\pgfplotsset{compat = newest}

\pgfplotsset{
  log y ticks with fixed point/.style={
      yticklabel={
        \pgfkeys{/pgf/fpu=true}
        \pgfmathparse{exp(\tick)}%
        \pgfmathprintnumber[fixed relative, precision=3]{\pgfmathresult}
        \pgfkeys{/pgf/fpu=false}
      }
  }
}

% 读取原始数据
\pgfplotstableread[col sep=comma,header=true]{
M,A,B,C,D,E,F,G
0,1500000,0,0,0,0,0,0
1,0,300,0,0,0,0,50
2,0,0,1000000,0,50000,0,0
3,0,0,0,10000,0,500,50
}\tempdata

% 将数据中的0替换为1,避免log(0)报错,同时作为堆叠基线
\pgfplotstableedit[
    create on use/A/.style={create col/expr={\thisrow{A} == 0 ? 1 : \thisrow{A}}},
    create on use/B/.style={create col/expr={\thisrow{B} == 0 ? 1 : \thisrow{B}}},
    create on use/C/.style={create col/expr={\thisrow{C} == 0 ? 1 : \thisrow{C}}},
    create on use/D/.style={create col/expr={\thisrow{D} == 0 ? 1 : \thisrow{D}}},
    create on use/E/.style={create col/expr={\thisrow{E} == 0 ? 1 : \thisrow{E}}},
    create on use/F/.style={create col/expr={\thisrow{F} == 0 ? 1 : \thisrow{F}}},
    create on use/G/.style={create col/expr={\thisrow{G} == 0 ? 1 : \thisrow{G}}},
]\data{\tempdata}

\begin{document}

\begin{figure}[htbp]
\centering
\begin{tikzpicture}
\begin{axis}[
    ybar stacked,
    ymode=log,
    ymin=1, ymax=1e7, % Y轴范围10^0到10^7
    ylabel = Time (in seconds),
    xtick = {0, 1, 2, 3},
    xlabel style = {font=\small},
    ylabel style = {font=\small},
    yticklabel style = {font=\small},
    xticklabel style = {font=\small},
    ytick={1,10,100,1000,1e4,1e5,1e6,1e7}, % 明确刻度点
    log y ticks with fixed point, % 转换刻度为常规数值显示
    bar width=0.8, % 消除条形间隙
    axis on top, % 刻度线置于条形上方
    legend pos=north east,
    legend style={font=\small}
]
  \addplot table[x=M,y=A] from \data; \addlegendentry{A}
  \addplot table[x=M,y=B] from \data; \addlegendentry{B}
  \addplot table[x=M,y=C] from \data; \addlegendentry{C}
  \addplot table[x=M,y=D] from \data; \addlegendentry{D}
  \addplot table[x=M,y=E] from \data; \addlegendentry{E}
  \addplot table[x=M,y=F] from \data; \addlegendentry{F}
  \addplot table[x=M,y=G] from \data; \addlegendentry{G}
\end{axis}
\end{tikzpicture}
\end{figure}

\end{document}

关键修改说明

  • 处理0值问题:通过\pgfplotstableedit将所有0替换为1,既避免log(0)的报错,又让1作为对数轴的基线(对应10^0),不影响非0数据的堆叠高度。
  • 对数轴配置:启用ymode=log,明确设置ymin=1和ymax=1e7,匹配你要求的100到107范围。
  • 优化刻度显示:自定义ytick刻度点,配合log y ticks with fixed point样式,将对数刻度转换为易读的常规数值。
  • 消除堆叠间隙:设置bar width=0.8让条形紧密排列,axis on top确保刻度线不被条形遮挡。
  • 添加图例:方便区分不同系列的堆叠部分,提升图表可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 12:54:51