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

如何让TikZ绘制的树状图主节点居中并调整节点内文字边距

优化方案

针对你遇到的两个问题,可通过以下修改解决:

1. 修复主节点居中问题

原代码错误将主节点挂载在空坐标点的子节点,且grow参数错误传入了长度值0ex(该参数应为角度值),导致主节点位置偏移。修改方案:

  • 直接将主节点作为根节点向下延伸子节点,主节点会自动和下方一级子节点的中心对齐
  • 调整一级节点的sibling distance适配主节点宽度,避免一级节点内容溢出

2. 解决节点文字排版过密问题

在节点样式中增加内边距参数即可,可按需设置以下属性:

  • inner xsep:节点左右内边距
  • inner ysep:节点上下内边距
  • 文字过长的节点可额外增加text width属性设置固定宽度,实现自动换行

额外优化点

  • 删除重复定义的fourth样式
  • 删除未使用的forest包引用,减少冗余加载

修改后的完整代码如下:

\documentclass[tikz,border=10pt]{standalone}
\usetikzlibrary{shadows,trees}
\tikzset{every shadow/.style={shadow xshift=5pt,shadow yshift=-5pt}}
\begin{document}

\begin{tikzpicture}[
  % 增加内边距解决文字过密问题
  man/.style={rectangle,draw,fill=gray!20,inner xsep=1em,inner ysep=0.6em},
  woman/.style={rectangle,draw,fill=gray!20,rounded corners=.8ex,inner xsep=0.8em,inner ysep=0.4em},
  grandchild/.style={grow=down,xshift=1em,anchor=west,
    edge from parent path={(\tikzparentnode.south) |- (\tikzchildnode.west)}},
  first/.style={level distance=6ex},
  second/.style={level distance=12ex},
  third/.style={level distance=18ex},
  fourth/.style={level distance=24ex},
  fifth/.style={level distance=29ex},
  % 调整一级节点间距适配主节点宽度
  level 1/.style={sibling distance=18em}]
    % 直接将主节点设为根节点
    \node[man]{Challenges:Blockchain-based Digital Twins}
    [edge from parent fork down,grow=down]
    child{node[man]
    {Technical Challenges}
      child[grandchild,first] {node[woman]{High-fidelity Models}}
      child[grandchild,second] {node[woman]{Data-related Issues}}
      child[grandchild,third] {node[woman] {Model Challenges}}
      child[grandchild,fourth] {node[woman] {Uncertain Events}}
      child[grandchild,fifth] {node[woman] {Interoperability}}
      }
    child{node[man]
    {Logistical Challenges}
    child[grandchild,first] {node[woman]{Standardization Barriers}}
    child[grandchild,second] {node[woman]{Scattered Ownership of Data}}
    child[grandchild,third] {node[woman] {Infrastructure Cost}}
    child[grandchild,fourth] {node[woman] {Skepticism in Blockchain}}
    }
    child{node[man]
    {Social Challenges}
    child[grandchild,first] {node[woman]{Ethical and Moral Issues}}
    child[grandchild,second] {node[woman]{Environmental Issues}}
    child[grandchild,third] {node[woman] {Lack of Collaboration}}
    child[grandchild,fourth] {node[woman] {Lack of Sharing Sensitive Information}}
    };
\end{tikzpicture}

\end{document}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:36:05