sphinx中使用mermaid画图

目前博客中的图片使用graphviz生成, 当要绘制复杂图形时很困难. 相对使用mermaid比较简单.

config.py

安装sphinxcontrib-mermaid后, 在config.py中的加上扩展支持

1
2
3
4
5
6
7
8
9
extensions = [
    'sphinxcontrib.mermaid',
    # ...
]
mermaid_output_format = 'raw'
mermaid_version = ''
html_js_files = [
    'js/mermaid.js'
]

如果需要生成png图片, 还需要安装nodejs, mermaid, mermaid-cli等 包, 这里只是在浏览器中使用.

序列图

RST中加入

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
.. mermaid::

   sequenceDiagram
     participant Alice
     participant Bob
     Alice->John: Hello John, how are you?
     loop Healthcheck
       John->John: Fight against hypochondria
     end
     Note right of John: Rational thoughts <br/>prevail...
     John-->Alice: Great!
     John->Bob: How about you?
     Bob-->John: Jolly good!

生成图形:

sequenceDiagram participant Alice participant Bob Alice->John: Hello John, how are you? loop Healthcheck John->John: Fight against hypochondria end Note right of John: Rational thoughts <br/>prevail... John-->Alice: Great! John->Bob: How about you? Bob-->John: Jolly good!

普通二叉树图形

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
.. mermaid::

   graph TB
     A --- B & C
     B --- D & E
     C --- F & G
     D -- left --- H
     D -- right --- J
     E -- left --- K
     E -- right --- L
     F -- left --- M
     F -- right --- N
     G -- left --- O
     G -- right --- P

生成图形

graph TB A --- B & C B --- D & E C --- F & G D -- left --- H D -- right --- J E -- left --- K E -- right --- L F -- left --- M F -- right --- N G -- left --- O G -- right --- P