【Mermaid】ダイアグラム作成の詳細 - 高度なカスタマイズと実例

PUBLISHED 2024-08-18

この記事では、Mermaid(マーメイド)を使ったダイアグラム作成の高度なテクニックを解説します。Mermaidとは、テキストベースの記法でフローチャートやシーケンス図、クラス図などを生成できるJavaScriptライブラリです。Markdownドキュメントに埋め込むことで、コードと図表を一元管理できる点が大きな特徴です。

本ガイドでは、基本的なノード接続から、サブグラフ(グループ化)、テーマのカスタマイズ、個別スタイル設定まで、実践的なコード例とともに詳しく説明します。技術ドキュメントやプレゼンテーション資料の作成に役立つテクニックを習得しましょう。

フローチャートの基本

ノードの接続

Mermaidを使う際の基本は「ノードの接続」です。ノード同士を様々な線で接続することで、フローチャートを構成します。

flowchart LR
    A[開始] --> B[処理1] --> C[処理2] --> D[終了]
%%{init: {'theme':'neutral'}}%% flowchart LR A[開始] --> B[処理1] --> C[処理2] --> D[終了]

ノードの種類

Mermaidでは、用途に応じて様々な形のノードを使うことができます。

記法形状用途
[テキスト]四角形一般的な処理
(テキスト)角丸四角形処理・操作
([テキスト])スタジアム型開始・終了
[[テキスト]]サブルーチンサブプロセス
[(テキスト)]円柱形データベース
((テキスト))円形接続点
{テキスト}ひし形条件分岐
{{テキスト}}六角形準備
[/テキスト/]平行四辺形入力
[\テキスト\]逆平行四辺形出力
flowchart TB
    A["四角形ノード"] --> B(("円形ノード")) --> C{"ひし形ノード"}
    D([スタジアム型]) --> E[(データベース)] --> F{{六角形}}
%%{init: {'theme':'neutral'}}%% flowchart TB A["四角形ノード"] --> B(("円形ノード")) --> C{"ひし形ノード"} D([スタジアム型]) --> E[(データベース)] --> F{{六角形}}

ダイアグラムの方向

フローチャートの方向を設定するには、flowchartの横に方向を指定します。

指定方向
TB または TD上から下(Top to Bottom)
BT下から上(Bottom to Top)
LR左から右(Left to Right)
RL右から左(Right to Left)
flowchart LR
    A --> B --> C
%%{init: {'theme':'neutral'}}%% flowchart LR A --> B --> C

線のスタイル

基本的な線の種類

ノード間に様々なスタイルの線を引くことができます。

flowchart LR
    A -->|矢印| B
    C ---|線のみ| D
    E ==>|太い矢印| F
    G -.->|点線矢印| H
    I -.-|点線| J
%%{init: {'theme':'neutral'}}%% flowchart LR A -->|矢印| B C ---|線のみ| D E ==>|太い矢印| F G -.->|点線矢印| H I -.-|点線| J

特殊な接続

flowchart LR
    A o--o B
    C x--x D
    E <--> F
%%{init: {'theme':'neutral'}}%% flowchart LR A o--o B C x--x D E <--> F

線の長さの調整

ハイフンや等号の数を増やすことで、線の長さを調整できます。

flowchart LR
    A --> B
    C ---> D
    E ----> F
%%{init: {'theme':'neutral'}}%% flowchart LR A --> B C ---> D E ----> F

サブグラフ(グループ化)

基本的なサブグラフ

ノードをグループ化して、複雑なチャートを構成することができます。

flowchart TB
    subgraph グループ1
        A --> B
    end
    subgraph グループ2
        C --> D
    end
    グループ1 --> グループ2
%%{init: {'theme':'neutral'}}%% flowchart TB subgraph グループ1 A --> B end subgraph グループ2 C --> D end グループ1 --> グループ2

ネストしたサブグラフ

サブグラフの中にさらにサブグラフを含めることも可能です。

flowchart TB
    subgraph 外側
        subgraph 内側1
            A --> B
        end
        subgraph 内側2
            C --> D
        end
        内側1 --> 内側2
    end
%%{init: {'theme':'neutral'}}%% flowchart TB subgraph 外側 subgraph 内側1 A --> B end subgraph 内側2 C --> D end 内側1 --> 内側2 end

サブグラフの方向指定

サブグラフ内の方向を個別に指定できます。

flowchart LR
    subgraph TOP
        direction TB
        A --> B
    end
    subgraph BOTTOM
        direction TB
        C --> D
    end
    TOP --> BOTTOM
%%{init: {'theme':'neutral'}}%% flowchart LR subgraph TOP direction TB A --> B end subgraph BOTTOM direction TB C --> D end TOP --> BOTTOM

シーケンス図

シーケンス図は、オブジェクト間のメッセージのやり取りを時系列で表現します。

基本的なシーケンス図

sequenceDiagram
    participant U as ユーザー
    participant S as サーバー
    participant D as データベース

    U->>S: リクエスト送信
    S->>D: クエリ実行
    D-->>S: 結果返却
    S-->>U: レスポンス返却
%%{init: {'theme':'neutral'}}%% sequenceDiagram participant U as ユーザー participant S as サーバー participant D as データベース U->>S: リクエスト送信 S->>D: クエリ実行 D-->>S: 結果返却 S-->>U: レスポンス返却

メッセージの種類

記法説明
->実線(矢印なし)
-->点線(矢印なし)
->>実線(矢印あり)
-->>点線(矢印あり)
-x実線(×印)
--x点線(×印)
-)実線(非同期)
--)点線(非同期)

アクティベーションとノート

sequenceDiagram
    participant A as クライアント
    participant B as サーバー

    A->>+B: 処理開始
    Note right of B: サーバーで<br/>処理中...
    B-->>-A: 処理完了

    Note over A,B: 通信終了
%%{init: {'theme':'neutral'}}%% sequenceDiagram participant A as クライアント participant B as サーバー A->>+B: 処理開始 Note right of B: サーバーで処理中... B-->>-A: 処理完了 Note over A,B: 通信終了

ループと条件分岐

sequenceDiagram
    participant C as クライアント
    participant S as サーバー

    C->>S: ログイン要求

    alt 認証成功
        S-->>C: トークン発行
    else 認証失敗
        S-->>C: エラー返却
    end

    loop ポーリング
        C->>S: ステータス確認
        S-->>C: 現在の状態
    end
%%{init: {'theme':'neutral'}}%% sequenceDiagram participant C as クライアント participant S as サーバー C->>S: ログイン要求 alt 認証成功 S-->>C: トークン発行 else 認証失敗 S-->>C: エラー返却 end loop ポーリング C->>S: ステータス確認 S-->>C: 現在の状態 end

クラス図

オブジェクト指向設計のクラス関係を表現します。

基本的なクラス図

classDiagram
    class Animal {
        +String name
        +int age
        +makeSound() void
    }

    class Dog {
        +String breed
        +bark() void
    }

    class Cat {
        +String color
        +meow() void
    }

    Animal <|-- Dog
    Animal <|-- Cat
%%{init: {'theme':'neutral'}}%% classDiagram class Animal { +String name +int age +makeSound() void } class Dog { +String breed +bark() void } class Cat { +String color +meow() void } Animal <|-- Dog Animal <|-- Cat

関係性の種類

記法説明
<|--継承
*--コンポジション
o--集約
-->関連
--リンク
..>依存
..|>実装

多重度の指定

classDiagram
    Customer "1" --> "*" Order : places
    Order "*" --> "1..*" Product : contains
%%{init: {'theme':'neutral'}}%% classDiagram Customer "1" --> "*" Order : places Order "*" --> "1..*" Product : contains

ER図(Entity Relationship Diagram)

データベースのテーブル関係を表現します。

erDiagram
    CUSTOMER ||--o{ ORDER : places
    ORDER ||--|{ LINE_ITEM : contains
    PRODUCT ||--o{ LINE_ITEM : included_in

    CUSTOMER {
        int id PK
        string name
        string email
    }

    ORDER {
        int id PK
        int customer_id FK
        date created_at
    }

    PRODUCT {
        int id PK
        string name
        float price
    }

    LINE_ITEM {
        int order_id FK
        int product_id FK
        int quantity
    }
%%{init: {'theme':'neutral'}}%% erDiagram CUSTOMER ||--o{ ORDER : places ORDER ||--|{ LINE_ITEM : contains PRODUCT ||--o{ LINE_ITEM : included_in CUSTOMER { int id PK string name string email } ORDER { int id PK int customer_id FK date created_at } PRODUCT { int id PK string name float price } LINE_ITEM { int order_id FK int product_id FK int quantity }

カーディナリティの記法

記法意味
||1つ(必須)
o|0または1
}o0以上
}|1以上

ガントチャート

プロジェクトのスケジュールを表現します。

gantt
    title プロジェクトスケジュール
    dateFormat YYYY-MM-DD

    section 企画
    要件定義     :a1, 2024-01-01, 7d
    設計         :a2, after a1, 14d

    section 開発
    フロントエンド :b1, after a2, 21d
    バックエンド   :b2, after a2, 28d

    section テスト
    単体テスト    :c1, after b1, 7d
    結合テスト    :c2, after b2, 14d

    section リリース
    デプロイ      :d1, after c2, 3d
%%{init: {'theme':'neutral'}}%% gantt title プロジェクトスケジュール dateFormat YYYY-MM-DD section 企画 要件定義 :a1, 2024-01-01, 7d 設計 :a2, after a1, 14d section 開発 フロントエンド :b1, after a2, 21d バックエンド :b2, after a2, 28d section テスト 単体テスト :c1, after b1, 7d 結合テスト :c2, after b2, 14d section リリース デプロイ :d1, after c2, 3d

タスクの状態

gantt
    title タスク状態の例
    dateFormat YYYY-MM-DD

    完了タスク    :done, t1, 2024-01-01, 5d
    進行中タスク   :active, t2, after t1, 5d
    予定タスク    :t3, after t2, 5d
    クリティカル   :crit, t4, after t3, 5d
    マイルストーン :milestone, m1, after t4, 0d
%%{init: {'theme':'neutral'}}%% gantt title タスク状態の例 dateFormat YYYY-MM-DD 完了タスク :done, t1, 2024-01-01, 5d 進行中タスク :active, t2, after t1, 5d 予定タスク :t3, after t2, 5d クリティカル :crit, t4, after t3, 5d マイルストーン :milestone, m1, after t4, 0d

状態遷移図

オブジェクトの状態変化を表現します。

stateDiagram-v2
    [*] --> 待機中
    待機中 --> 処理中: 開始
    処理中 --> 完了: 成功
    処理中 --> エラー: 失敗
    エラー --> 待機中: リトライ
    完了 --> [*]
%%{init: {'theme':'neutral'}}%% stateDiagram-v2 [*] --> 待機中 待機中 --> 処理中: 開始 処理中 --> 完了: 成功 処理中 --> エラー: 失敗 エラー --> 待機中: リトライ 完了 --> [*]

複合状態

stateDiagram-v2
    [*] --> Active

    state Active {
        [*] --> Idle
        Idle --> Running: start
        Running --> Idle: stop
    }

    Active --> Inactive: deactivate
    Inactive --> Active: activate
    Inactive --> [*]
%%{init: {'theme':'neutral'}}%% stateDiagram-v2 [*] --> Active state Active { [*] --> Idle Idle --> Running: start Running --> Idle: stop } Active --> Inactive: deactivate Inactive --> Active: activate Inactive --> [*]

円グラフ

pie showData
    title プログラミング言語の使用率
    "JavaScript" : 30
    "Python" : 25
    "Java" : 20
    "TypeScript" : 15
    "その他" : 10
%%{init: {'theme':'neutral'}}%% pie showData title プログラミング言語の使用率 "JavaScript" : 30 "Python" : 25 "Java" : 20 "TypeScript" : 15 "その他" : 10

クリック可能なノード

ノードをクリック可能にし、特定のアクション(リンクや関数の呼び出し)に結びつけることができます。

flowchart LR
    A[クリック可能なノード]
    B[別のリンク]
    A --> B
    click A href "https://mermaid.js.org/" "Mermaid公式サイト" _blank
    click B href "https://github.com/mermaid-js/mermaid" "GitHubリポジトリ" _blank
%%{init: {'theme':'neutral'}}%% flowchart LR A[クリック可能なノード] B[別のリンク] A --> B click A href "https://mermaid.js.org/" "Mermaid公式サイト" _blank click B href "https://github.com/mermaid-js/mermaid" "GitHubリポジトリ" _blank

テーマとスタイル

ビルトインテーマ

Mermaidにはテーマ機能があり、デザインを簡単に変更できます。

テーマ名説明
defaultデフォルトテーマ
forest緑を基調としたテーマ
darkダークモード
neutralモノクロテーマ
baseカスタマイズ用の基本テーマ
%%{init: {'theme':'forest'}}%%
flowchart LR
    A --> B --> C
%%{init: {'theme':'neutral'}}%% %%{init: {'theme':'forest'}}%% flowchart LR A --> B --> C

ノードの個別スタイル設定

ノードごとにスタイルを変更する場合は、styleディレクティブを使用します。

graph LR
    A --> B --> C
    style A fill:#e1f5fe,stroke:#01579b,stroke-width:2px
    style B fill:#f3e5f5,stroke:#4a148c,stroke-width:2px
    style C fill:#fff3e0,stroke:#e65100,stroke-width:2px
%%{init: {'theme':'neutral'}}%% graph LR A --> B --> C style A fill:#e1f5fe,stroke:#01579b,stroke-width:2px style B fill:#f3e5f5,stroke:#4a148c,stroke-width:2px style C fill:#fff3e0,stroke:#e65100,stroke-width:2px

クラスを使ったスタイル定義

複数のノードに同じスタイルを適用する場合は、クラスを定義します。

graph LR
    A:::important --> B:::normal --> C:::warning

    classDef important fill:#ffcdd2,stroke:#b71c1c,stroke-width:3px
    classDef normal fill:#e3f2fd,stroke:#1565c0
    classDef warning fill:#fff9c4,stroke:#f57f17,stroke-width:2px
%%{init: {'theme':'neutral'}}%% graph LR A:::important --> B:::normal --> C:::warning classDef important fill:#ffcdd2,stroke:#b71c1c,stroke-width:3px classDef normal fill:#e3f2fd,stroke:#1565c0 classDef warning fill:#fff9c4,stroke:#f57f17,stroke-width:2px

線のカーブやノード間の距離の調整

線のカーブを変更するには、flowchartのオプションにcurveを指定します。また、ノード間の距離はnodeSpacingrankSpacingで調整可能です。

%%{init: { 'flowchart': { 'curve': 'basis', 'nodeSpacing': 50, 'rankSpacing': 100 } } }%%
flowchart LR
    A --> B --> C --> D --> E
%%{init: {'theme':'neutral'}}%% %%{init: { 'flowchart': { 'curve': 'basis', 'nodeSpacing': 50, 'rankSpacing': 100 } } }%% flowchart LR A --> B --> C --> D --> E

実践例

複雑な決定ツリー

複雑な条件分岐のあるフローチャートも簡単に作成できます。

graph TD
    A[開始] --> B{ユーザー認証}
    B -->|成功| C{権限確認}
    B -->|失敗| D[ログイン画面へ]
    C -->|管理者| E[管理画面]
    C -->|一般ユーザー| F[ユーザー画面]
    C -->|ゲスト| G[閲覧のみ]
    E --> H[終了]
    F --> H
    G --> H
    D --> A
%%{init: {'theme':'neutral'}}%% graph TD A[開始] --> B{ユーザー認証} B -->|成功| C{権限確認} B -->|失敗| D[ログイン画面へ] C -->|管理者| E[管理画面] C -->|一般ユーザー| F[ユーザー画面] C -->|ゲスト| G[閲覧のみ] E --> H[終了] F --> H G --> H D --> A

マイクロサービスアーキテクチャ

graph TB
    subgraph クライアント
        Web[Webアプリ]
        Mobile[モバイルアプリ]
    end

    subgraph APIゲートウェイ
        Gateway[API Gateway]
    end

    subgraph マイクロサービス
        Auth[認証サービス]
        User[ユーザーサービス]
        Order[注文サービス]
        Payment[決済サービス]
    end

    subgraph データストア
        AuthDB[(認証DB)]
        UserDB[(ユーザーDB)]
        OrderDB[(注文DB)]
    end

    Web --> Gateway
    Mobile --> Gateway
    Gateway --> Auth
    Gateway --> User
    Gateway --> Order
    Gateway --> Payment
    Auth --> AuthDB
    User --> UserDB
    Order --> OrderDB
%%{init: {'theme':'neutral'}}%% graph TB subgraph クライアント Web[Webアプリ] Mobile[モバイルアプリ] end subgraph APIゲートウェイ Gateway[API Gateway] end subgraph マイクロサービス Auth[認証サービス] User[ユーザーサービス] Order[注文サービス] Payment[決済サービス] end subgraph データストア AuthDB[(認証DB)] UserDB[(ユーザーDB)] OrderDB[(注文DB)] end Web --> Gateway Mobile --> Gateway Gateway --> Auth Gateway --> User Gateway --> Order Gateway --> Payment Auth --> AuthDB User --> UserDB Order --> OrderDB

まとめ

Mermaidは、直感的な構文で複雑なダイアグラムを簡単に作成できる強力なツールです。この記事で紹介した主なダイアグラムは以下の通りです。

  • フローチャート: プロセスや処理の流れを表現
  • シーケンス図: オブジェクト間のやり取りを時系列で表現
  • クラス図: オブジェクト指向設計のクラス関係を表現
  • ER図: データベースのテーブル関係を表現
  • ガントチャート: プロジェクトのスケジュールを表現
  • 状態遷移図: オブジェクトの状態変化を表現
  • 円グラフ: データの割合を視覚化

カスタマイズ性も高く、テーマの変更、ノードのスタイル設定、線のカーブ調整など、様々なニーズに対応できます。プロジェクトのニーズに合った美しい視覚表現を実現してみてください。

参考文献

CATEGORY
TAGS
円