Skip to content

Markdown Diagrams

Beyond text and mathematical formulas, diagrams are also important elements in documents. While standard Markdown doesn't support diagrams, you can create flowcharts, sequence diagrams, Gantt charts, and more through integrated diagramming tools. This chapter introduces how to draw various diagrams in Markdown.

Mermaid Introduction

Mermaid is a JavaScript-based diagramming tool that allows you to create various diagrams in Markdown using simple text syntax.

Basic Syntax

Use three backticks with mermaid identifier:

markdown
```mermaid
graph TD;
    A-->B;

## Flowcharts

### Basic Flowchart

```markdown
```mermaid
graph TD;
    A[Start] --> B{Decision};
    B -->|Yes| C[Execute];
    B -->|No| D[Skip];
    C --> E[End];
    D --> E;

**Result:**

```mermaid
graph TD;
    A[Start] --> B{Decision};
    B -->|Yes| C[Execute];
    B -->|No| D[Skip];
    C --> E[End];
    D --> E;

Left-to-Right Flowchart

markdown
```mermaid
graph LR;
    A[Start] --> B[Process];
    B --> C[End];

**Result:**

```mermaid
graph LR;
    A[Start] --> B[Process];
    B --> C[End];

Complex Flowchart

markdown
```mermaid
graph TD;
    Start(Start) --> Init[Initialize];
    Init --> Check{Check condition};
    Check -->|Success| Process[Process data];
    Check -->|Failure| Error[Log error];
    Process --> Save[Save result];
    Error --> Retry{Retry?};
    Retry -->|Yes| Init;
    Retry -->|No| End(End);
    Save --> End;

**Result:**

```mermaid
graph TD;
    Start(Start) --> Init[Initialize];
    Init --> Check{Check condition};
    Check -->|Success| Process[Process data];
    Check -->|Failure| Error[Log error];
    Process --> Save[Save result];
    Error --> Retry{Retry?};
    Retry -->|Yes| Init;
    Retry -->|No| End(End);
    Save --> End;

Node Shapes

markdown
```mermaid
graph TD;
    A[Square node] --> B(Rounded node);
    B --> C([Circle node]);
    C --> D[(Cylinder)];
    D --> E{{Subroutine}};

**Result:**

```mermaid
graph TD;
    A[Square node] --> B(Rounded node);
    B --> C([Circle node]);
    C --> D[(Cylinder)];
    D --> E{{Subroutine}};

Sequence Diagrams

Basic Sequence Diagram

markdown
```mermaid
sequenceDiagram;
    participant A as User
    participant B as System
    A->>B: Send request
    B-->>A: Return response

**Result:**

```mermaid
sequenceDiagram;
    participant A as User
    participant B as System
    A->>B: Send request
    B-->>A: Return response

Complete Login Flow

markdown
```mermaid
sequenceDiagram;
    participant User as User
    participant Frontend as Frontend
    participant Backend as Backend
    participant DB as Database

    User->>Frontend: Enter username and password
    Frontend->>Backend: Send login request
    Backend->>DB: Query user info
    DB-->>Backend: Return user data
    Backend-->>Frontend: Return auth token
    Frontend-->>User: Login successful

**Result:**

```mermaid
sequenceDiagram;
    participant User as User
    participant Frontend as Frontend
    participant Backend as Backend
    participant DB as Database

    User->>Frontend: Enter username and password
    Frontend->>Backend: Send login request
    Backend->>DB: Query user info
    DB-->>Backend: Return user data
    Backend-->>Frontend: Return auth token
    Frontend-->>User: Login successful

Activation and Loops

markdown
```mermaid
sequenceDiagram;
    participant A as Client
    participant B as Server

    A->>B: Request data
    activate B
    B->>B: Process request
    loop Retry 3 times
        B->>B: Try to fetch
    end
    B-->>A: Return result
    deactivate B

**Result:**

```mermaid
sequenceDiagram;
    participant A as Client
    participant B as Server

    A->>B: Request data
    activate B
    B->>B: Process request
    loop Retry 3 times
        B->>B: Try to fetch
    end
    B-->>A: Return result
    deactivate B

Gantt Charts

Basic Gantt Chart

markdown
```mermaid
gantt
    title Project Development Plan
    dateFormat  YYYY-MM-DD
    section Design
    Requirements analysis      :2024-01-01, 5d
    System design      :after requirements analysis, 7d
    section Development
    Frontend development      :2024-01-13, 10d
    Backend development      :2024-01-13, 12d
    section Testing
    Functional testing      :2024-01-25, 5d
    Deployment上线      :2024-01-30, 2d

**Result:**

```mermaid
gantt
    title Project Development Plan
    dateFormat  YYYY-MM-DD
    section Design
    Requirements analysis      :2024-01-01, 5d
    System design      :after requirements analysis, 7d
    section Development
    Frontend development      :2024-01-13, 10d
    Backend development      :2024-01-13, 12d
    section Testing
    Functional testing      :2024-01-25, 5d
    Deployment上线      :2024-01-30, 2d

Complete Project Management

markdown
```mermaid
gantt
    title Software Development Project
    dateFormat  YYYY-MM-DD
    axisFormat  %m-%d

    section Planning
    Project kickoff      :p1, 2024-01-01, 2d
    Requirements gathering      :p2, after p1, 5d
    Requirements review      :p3, after p2, 1d

    section Design
    Architecture design      :d1, after p3, 4d
    Database design    :d2, after d1, 3d
    UI design       :d3, after d1, 5d

    section Development
    Backend development      :dev1, after d2, 15d
    Frontend development      :dev2, after d3, 12d
    API integration      :dev3, after dev1 dev2, 3d

    section Testing
    Unit testing      :t1, after dev1, 3d
    Integration testing      :t2, after dev3, 4d
    User testing      :t3, after t2, 5d

    section Deployment
    Pre-release deployment    :dp1, after t3, 2d
    Official launch      :dp2, after dp1, 1d

**Result:**

```mermaid
gantt
    title Software Development Project
    dateFormat  YYYY-MM-DD
    axisFormat  %m-%d

    section Planning
    Project kickoff      :p1, 2024-01-01, 2d
    Requirements gathering      :p2, after p1, 5d
    Requirements review      :p3, after p2, 1d

    section Design
    Architecture design      :d1, after p3, 4d
    Database design    :d2, after d1, 3d
    UI design       :d3, after d1, 5d

    section Development
    Backend development      :dev1, after d2, 15d
    Frontend development      :dev2, after d3, 12d
    API integration      :dev3, after dev1 dev2, 3d

    section Testing
    Unit testing      :t1, after dev1, 3d
    Integration testing      :t2, after dev3, 4d
    User testing      :t3, after t2, 5d

    section Deployment
    Pre-release deployment    :dp1, after t3, 2d
    Official launch      :dp2, after dp1, 1d

State Diagrams

Basic State Diagram

markdown
```mermaid
stateDiagram-v2
    [*] --> Pending
    Pending --> Processing
    Processing --> Completed
    Processing --> Cancelled
    Completed --> [*]
    Cancelled --> [*]

**Result:**

```mermaid
stateDiagram-v2
    [*] --> Pending
    Pending --> Processing
    Processing --> Completed
    Processing --> Cancelled
    Completed --> [*]
    Cancelled --> [*]

Complex State Diagram

markdown
```mermaid
stateDiagram-v2
    [*] --> Offline
    Offline --> Logging in
    Logging in --> Online
    Logging in --> Offline : Login failed
    Online --> Busy
    Online --> Offline
    Online --> Invisible
    Busy --> Online
    Busy --> Offline
    Invisible --> Online

**Result:**

```mermaid
stateDiagram-v2
    [*] --> Offline
    Offline --> Logging in
    Logging in --> Online
    Logging in --> Offline : Login failed
    Online --> Busy
    Online --> Offline
    Online --> Invisible
    Busy --> Online
    Busy --> Offline
    Invisible --> Online

Class Diagrams

Basic Class Diagram

markdown
```mermaid
classDiagram
    class Animal {
        +String name
        +int age
        +eat()
        +sleep()
    }
    class Dog {
        +bark()
    }
    class Cat {
        +meow()
    }
    Animal <|-- Dog
    Animal <|-- Cat

**Result:**

```mermaid
classDiagram
    class Animal {
        +String name
        +int age
        +eat()
        +sleep()
    }
    class Dog {
        +bark()
    }
    class Cat {
        +meow()
    }
    Animal <|-- Dog
    Animal <|-- Cat

Complete Class Diagram

markdown
```mermaid
classDiagram
    class User {
        -String username
        -String password
        -String email
        +login()
        +logout()
        +updateProfile()
    }
    class Admin {
        +addUser()
        +deleteUser()
        +viewLogs()
    }
    class Post {
        -String title
        -String content
        -DateTime createTime
        +publish()
        +edit()
        +delete()
    }
    class Comment {
        -String content
        -DateTime createTime
        +addComment()
        +deleteComment()
    }

    User <|-- Admin
    User "1" --> "*" Post : creates
    Post "1" --> "*" Comment : has

**Result:**

```mermaid
classDiagram
    class User {
        -String username
        -String password
        -String email
        +login()
        +logout()
        +updateProfile()
    }
    class Admin {
        +addUser()
        +deleteUser()
        +viewLogs()
    }
    class Post {
        -String title
        -String content
        -DateTime createTime
        +publish()
        +edit()
        +delete()
    }
    class Comment {
        -String content
        -DateTime createTime
        +addComment()
        +deleteComment()
    }

    User <|-- Admin
    User "1" --> "*" Post : creates
    Post "1" --> "*" Comment : has

Entity Relationship Diagrams

Basic ER Diagram

markdown
```mermaid
erDiagram
    CUSTOMER ||--o{ ORDER : places
    ORDER ||--|{ LINE-ITEM : contains
    CUSTOMER }|..|{ DELIVERY-ADDRESS : uses

**Result:**

```mermaid
erDiagram
    CUSTOMER ||--o{ ORDER : places
    ORDER ||--|{ LINE-ITEM : contains
    CUSTOMER }|..|{ DELIVERY-ADDRESS : uses

Database Design

markdown
```mermaid
erDiagram
    USER {
        int id PK
        string username
        string email
        datetime created_at
    }
    POST {
        int id PK
        int user_id FK
        string title
        text content
        datetime created_at
    }
    COMMENT {
        int id PK
        int post_id FK
        int user_id FK
        text content
        datetime created_at
    }

    USER ||--o{ POST : creates
    USER ||--o{ COMMENT : writes
    POST ||--o{ COMMENT : has

**Result:**

```mermaid
erDiagram
    USER {
        int id PK
        string username
        string email
        datetime created_at
    }
    POST {
        int id PK
        int user_id FK
        string title
        text content
        datetime created_at
    }
    COMMENT {
        int id PK
        int post_id FK
        int user_id FK
        text content
        datetime created_at
    }

    USER ||--o{ POST : creates
    USER ||--o{ COMMENT : writes
    POST ||--o{ COMMENT : has

Pie Charts

markdown
```mermaid
pie
    title Programming Language Usage Distribution
    "JavaScript" : 35
    "Python" : 25
    "Java" : 20
    "C++" : 12
    "Others" : 8

**Result:**

```mermaid
pie
    title Programming Language Usage Distribution
    "JavaScript" : 35
    "Python" : 25
    "Java" : 20
    "C++" : 12
    "Others" : 8

Mind Maps

markdown
```mermaid
mindmap
  root((Markdown))
    Basic Syntax
      Headings
      Lists
      Blockquotes
    Formatting
      Bold
      Italic
      Code
    Advanced Features
      Tables
      Links
      Images
    Extensions
      Math Formulas
      Diagrams
      Footnotes

**Result:**

```mermaid
mindmap
  root((Markdown))
    Basic Syntax
      Headings
      Lists
      Blockquotes
    Formatting
      Bold
      Italic
      Code
    Advanced Features
      Tables
      Links
      Images
    Extensions
      Math Formulas
      Diagrams
      Footnotes

Other Diagramming Tools

PlantUML

PlantUML is another popular diagramming tool:

markdown
```plantuml
@startuml
actor User
participant "Frontend System" as Front
participant "Backend System" as Back
database "Database" as DB

User -> Front: Login
Front -> Back: Validate
Back -> DB: Query
DB --> Back: Return data
Back --> Front: Login successful
Front --> User: Show homepage
@enduml

### Graphviz (DOT)

```markdown
```dot
digraph G {
    A -> B;
    B -> C;
    C -> D;
    D -> A;
}

## Diagram Best Practices

### 1. Keep It Simple

```markdown
✅ Simple and clear
```mermaid
graph LR;
    A-->B;

❌ Too complex

mermaid
graph LR;
    A-->B;
    B-->C;
    C-->D;
    ...

### 2. Add Titles

```markdown
```mermaid
gantt
    title Project Schedule
    ...

### 3. Use Meaningful Labels

```markdown
✅ Clear labels
A[Start] --> B{Decision}

❌ Vague labels
A[Step 1] --> B[Step 2]

4. Maintain Consistency

Use consistent diagram styles within your document.

Diagram Support on Different Platforms

GitHub

  • Full Mermaid support
  • Auto-rendering
  • Supports most diagram types

GitLab

  • Full Mermaid support
  • More features supported
  • Can use PlantUML

Typora

  • Real-time preview support
  • Export support
  • Custom themes

Obsidian

  • Native Mermaid support
  • Embed in notes
  • Diagram linking

Notion

  • No direct support
  • Can embed using Embed
  • Or use screenshots

Practical Examples

Technical Documentation

markdown
## System Architecture

```mermaid
graph TD;
    User[User] --> Web[Web Client];
    User --> Mobile[Mobile Client];
    Web --> API[API Gateway];
    Mobile --> API;
    API --> Auth[Auth Service];
    API --> Business[Business Service];
    Business --> DB[(Database)];
    Business --> Cache[Cache];

### API Documentation

```markdown
## User Registration Flow

```mermaid
sequenceDiagram;
    participant U as User
    participant F as Frontend
    participant A as API
    participant D as Database

    U->>F: Submit registration form
    F->>A: POST /api/register
    A->>D: Check if user exists
    D-->>A: Return result
    alt User doesn't exist
        A->>D: Create user
        D-->>A: Creation successful
        A-->>F: Return token
        F-->>U: Registration successful
    else User already exists
        A-->>F: Return error
        F-->>U: Prompt username already exists
    end

### Project Plan

```markdown
## Development Plan

```mermaid
gantt
    title Q1 Development Plan
    dateFormat  YYYY-MM-DD
    section Month 1
    Requirements analysis      :2024-01-01, 5d
    System design      :2024-01-06, 7d
    section Month 2
    Frontend development      :2024-01-13, 15d
    Backend development      :2024-01-13, 18d
    section Month 3
    Integration testing      :2024-01-31, 10d
    Online deployment      :2024-02-10, 3d

## Common Questions

### Q: Diagrams not displaying?

A: Check the following:
- Does the platform support Mermaid?
- Is the syntax correct?
- Are you using the correct identifier `mermaid`?

### Q: How to export diagrams?

A:
- Use screenshot tools
- Export from online editors
- Use Mermaid CLI

### Q: How to create complex diagrams?

A:
- Break down into multiple simple diagrams
- Use subgraph features
- Refer to official documentation

### Q: What if diagrams are too large?

A:
- Simplify diagram content
- Split into multiple diagrams
- Adjust layout direction

## Summary

This chapter detailed methods for drawing diagrams in Markdown:

- **Mermaid Tool**: Text-based diagramming tool
- **Flowcharts**: Describe processes and logic
- **Sequence Diagrams**: Show interaction processes
- **Gantt Charts**: Project progress management
- **State Diagrams**: State transition relationships
- **Class Diagrams**: Object-oriented design
- **Other Diagrams**: ER diagrams, pie charts, mind maps
- **Best Practices**: Keep simple, add titles, use meaningful labels

Mastering diagramming capabilities can make your documents more intuitive and easier to understand.

**Next:** Check [Markdown Learning Resources](./resources) to continue your learning journey.

Content is for learning and research only.