Mermaid: Diagram and Chart Tool | A Comprehensive Guide

Introduction to Mermaid

Mermaid is a JavaScript-based diagramming and charting tool that converts text-based definitions into visual diagrams. This approach allows users to create, modify, and maintain complex diagrams using simple syntax rather than graphical interfaces.

According to the official Mermaid documentation, this tool "lets you create diagrams and visualizations using text and code," aligning with modern documentation-as-code practices.


Key Capabilities

Mermaid provides several essential functions:

  • Text-to-diagram conversion: Generate diagrams from markdown-inspired syntax
  • Multiple diagram formats: Support for flowcharts, sequence diagrams, and more
  • Real-time visualization: See changes immediately in the preview pane
  • Export functionality: Save diagrams in SVG, PNG, and other formats
  • Browser-based operation: No software installation required

Research from GitHub Octoverse shows a 47% increase in diagram-as-code adoption since 2021, with Mermaid leading implementation.


Getting Started

Accessing the Tool

  1. The interface presents a code editor panel and a preview area

Basic Syntax Structure

Mermaid follows accessible markdown-inspired principles. Example of basic flowchart syntax:

graph TD
    A[Start] --> B{Decision}
    B -->|Yes| C[Process 1]
    B -->|No| D[Process 2]
    C --> E[End]
    D --> E

Available Diagram Types

TypeSyntax PrefixBest Used For
Flowchartgraph TDProcess workflows, decision trees
Sequence DiagramsequenceDiagramSystem interactions, message flows
Class DiagramclassDiagramObject relationships, inheritance
State DiagramstateDiagram-v2System states, transitions
C4 DiagramC4ContextSoftware architecture at different levels
Gantt ChartganttProject scheduling, timelines
Pie Chartpie titleData proportions, distributions
Entity RelationshiperDiagramDatabase structure, relationships
Git GraphgitGraphVersion control history, branches
User JourneyjourneyUser experience flows, satisfaction

These formats align with ISO/IEC 19510:2013 standards for visualization and modeling.


Creating Basic Diagrams

Flowchart Diagrams

Flowcharts visualize processes through connected nodes.

Construction Steps:

  1. Define direction: graph TD (top-down) or graph LR (left-right)
  2. Create nodes: A[Text] for rectangles, B{Text} for diamonds
  3. Connect nodes: A --> B for standard connections
  4. Add labels: A -->|Label text| B

Example Code:

graph TD
    A[Start] --> B[Research Problem]
    B --> C{Solution Found?}
    C -->|Yes| D[Implement Solution]
    C -->|No| E[Modify Approach]
    E --> B
    D --> F[End]

Output:

graph TD
    A[Start] --> B[Research Problem]
    B --> C{Solution Found?}
    C -->|Yes| D[Implement Solution]
    C -->|No| E[Modify Approach]
    E --> B
    D --> F[End]

try here

Research from the Journal of Visual Languages & Computing shows flowcharts improve problem-solving efficiency by 43% compared to text-only instructions.

Sequence Diagrams

Sequence diagrams illustrate interactions between components over time.

Construction Steps:

  1. Begin with sequenceDiagram declaration
  2. Define participants: participant Name
  3. Create message arrows: ParticipantA->>ParticipantB: Message text
  4. Add notes: Note over ParticipantA: Note text

Example Code:

sequenceDiagram
    participant User
    participant System
    User->>System: Login Request
    System->>User: Request Credentials
    User->>System: Submit Credentials
    System->>System: Validate
    System->>User: Authentication Result

Output:

sequenceDiagram
    participant User
    participant System
    User->>System: Login Request
    System->>User: Request Credentials
    User->>System: Submit Credentials
    System->>System: Validate
    System->>User: Authentication Result

try here

This format follows the UML 2.5 specification for interaction diagrams.


Creating Structural Diagrams

Class Diagrams

Class diagrams represent object relationships and structures.

Construction Steps:

  1. Begin with classDiagram declaration
  2. Define classes and attributes: class ClassName { +attribute: type +method() }
  3. Establish relationships: ClassA <|-- ClassB for inheritance

Example Code:

classDiagram
    class User {
        +String username
        +String email
        +login()
        +logout()
    }
    class Admin {
        +manageUsers()
    }
    User <|-- Admin

Output:

classDiagram
    class User {
        +String username
        +String email
        +login()
        +logout()
    }
    class Admin {
        +manageUsers()
    }
    User <|-- Admin

try here

Entity Relationship Diagrams

ERDs visualize database structure and relationships.

Construction Steps:

  1. Begin with erDiagram declaration
  2. Define entities and relationships: ENTITY1 ||--o{ ENTITY2 : relationship
  3. Add attributes within curly braces

Example Code:

erDiagram
    CUSTOMER ||--o{ ORDER : places
    CUSTOMER {
        string id
        string name
    }
    ORDER {
        string id
        date created_at
    }

Output:

erDiagram
    CUSTOMER ||--o{ ORDER : places
    CUSTOMER {
        string id
        string name
    }
    ORDER {
        string id
        date created_at
    }

try here

This notation follows database design standards described in "Database Design, Application Development, and Administration".


Creating Behavioral Diagrams

State Diagrams

State diagrams show system states and transitions.

Construction Steps:

  1. Begin with stateDiagram-v2 declaration
  2. Define states and transitions: StateA --> StateB: Action
  3. Mark start/end states: [*] --> FirstState and LastState --> [*]

Example Code:

stateDiagram-v2
    [*] --> Idle
    Idle --> Processing: Submit
    Processing --> Success: Complete
    Processing --> Error: Fail
    Success --> [*]
    Error --> Idle: Retry

Output:

stateDiagram-v2
    [*] --> Idle
    Idle --> Processing: Submit
    Processing --> Success: Complete
    Processing --> Error: Fail
    Success --> [*]
    Error --> Idle: Retry

try here

State diagrams conform to guidelines in NIST Special Publication 800-204 for system behavior representation.

User Journey Diagrams

User journey diagrams map experience flows and satisfaction.

Construction Steps:

  1. Begin with journey declaration
  2. Define sections: section Section Name
  3. Add steps with satisfaction scores: Step name: score: participants

Example Code:

journey
    title Onboarding Process
    section Registration
      Create account: 5: User
      Verify email: 3: User, System

Output:

journey
    title Onboarding Process
    section Registration
      Create account: 5: User
      Verify email: 3: User, System

try here

Nielsen Norman Group's journey mapping research indicates visual journey mapping increases team empathy by 74%.


Creating Planning Diagrams

Gantt Charts

Gantt charts visualize project schedules and dependencies.

Construction Steps:

  1. Begin with gantt declaration
  2. Set date format: dateFormat YYYY-MM-DD
  3. Define sections and tasks: Task name : taskId, date, duration
  4. Establish dependencies: Task : after taskId

Example Code:

gantt
    title Project Timeline
    dateFormat YYYY-MM-DD
    section Planning
    Requirements : a1, 2023-05-01, 10d
    section Development
    Implementation : a2, after a1, 15d
    Testing : a3, after a2, 5d

Output:

gantt
    title Project Timeline
    dateFormat YYYY-MM-DD
    section Planning
    Requirements : a1, 2023-05-01, 10d
    section Development
    Implementation : a2, after a1, 15d
    Testing : a3, after a2, 5d

try here

The Project Management Institute's PMBOK® Guide recognizes Gantt charts as a standard scheduling tool.

Git Graphs

Git graphs visualize version control history.

Construction Steps:

  1. Begin with gitGraph declaration
  2. Add commits: commit
  3. Create branches: branch branchName
  4. Switch branches: checkout branchName
  5. Merge branches: merge branchName

Example Code:

gitGraph
    commit
    branch develop
    checkout develop
    commit
    checkout main
    merge develop

Output:

gitGraph
    commit
    branch develop
    checkout develop
    commit
    checkout main
    merge develop

try here

According to GitLab's 2023 DevSecOps Report, teams with visualized branching strategies experience 35% fewer merge conflicts.


Creating Architectural Diagrams

C4 Diagrams

C4 diagrams document software architecture at multiple abstraction levels.

Construction Steps:

  1. Begin with C4Context declaration
  2. Define boundaries, systems, and people
  3. Establish relationships with Rel() function

Example Code:

C4Context
    title System Context diagram for Internet Banking System
    Enterprise_Boundary(b0, "BankBoundary") {
      Person(customer, "Banking Customer", "A customer of the bank")
      System(banking_system, "Internet Banking System", "Allows customers to view information about their bank accounts")
      
      Rel(customer, banking_system, "Uses")
    }
    System_Ext(email_system, "E-mail System", "The internal Microsoft Exchange e-mail system")
    System_Ext(mainframe, "Mainframe Banking System", "Stores all core banking information")
    
    Rel(banking_system, email_system, "Sends e-mail using")
    Rel(banking_system, mainframe, "Gets account information from")

Output:

C4Context
    title System Context diagram for Internet Banking System
    Enterprise_Boundary(b0, "BankBoundary") {
      Person(customer, "Banking Customer", "A customer of the bank")
      System(banking_system, "Internet Banking System", "Allows customers to view information about their bank accounts")
      
      Rel(customer, banking_system, "Uses")
    }
    System_Ext(email_system, "E-mail System", "The internal Microsoft Exchange e-mail system")
    System_Ext(mainframe, "Mainframe Banking System", "Stores all core banking information")
    
    Rel(banking_system, email_system, "Sends e-mail using")
    Rel(banking_system, mainframe, "Gets account information from")

try here

The C4 model is endorsed by ThoughtWorks Technology Radar as a recommended approach for architecture documentation.

Component Diagrams

Component diagrams show system architectural elements and connections.

Construction Steps:

  1. Use flowchart syntax with graph LR
  2. Create component nodes with appropriate shapes
  3. Group related components with subgraph

Example Code:

graph LR
    A[Web Client] --> B[API Gateway]
    B --> C[Authentication Service]
    subgraph Backend Services
        C
    end

Output:

graph LR
    A[Web Client] --> B[API Gateway]
    B --> C[Authentication Service]
    subgraph Backend Services
        C
    end

try here


Data Visualization Diagrams

Pie Charts

Pie charts show proportional data distribution.

Construction Steps:

  1. Begin with pie title Chart Title
  2. Add data points: "Label" : value

Example Code:

pie title Market Share
    "Product A" : 42.5
    "Product B" : 28.9
    "Product C" : 28.6

Output:

pie title Market Share
    "Product A" : 42.5
    "Product B" : 28.9
    "Product C" : 28.6

try here

Resource Breakdown Structure (RBS)

Resource breakdown structures illustrate project resources and their relationships, providing a structured overview for successful project completion. They categorize resources for easier planning, allocation, and control.

Construction Steps:

  1. Use flowchart syntax with graph TD
  2. Create hierarchical node connections
  3. Group related resources

Example Code:

graph TD
    A[Project Resources] --> B[Human Resources]
    A --> C[Material Resources]
    B --> B1[Project Manager]
    B --> B2[Technical Team]

Output:

graph TD
    A[Project Resources] --> B[Human Resources]
    A --> C[Material Resources]
    B --> B1[Project Manager]
    B --> B2[Technical Team]

try here

The RBS is recognized in the PMBOK® Guide as a critical resource planning tool.


Export and Integration

Available Output Formats

The Mermaid online tool provides several export options:

  • SVG Format: Vector-based graphics for scalable images
  • PNG Format: Bitmap images for general use
  • Source Code: Diagram definition text
  • Data URL: Embedded diagram data for web integration

The W3C SVG specification recommends SVG format for technical diagrams due to its accessibility features and scalability.

Integration Methods

Mermaid diagrams can be easily integrated with:

  • Documentation systems: Embed in markdown documents
  • Websites: Include via JavaScript or embedded images
  • Presentation software: Import as images
  • Version control systems: Store as text files alongside code

Best Practices

Diagram Creation Guidelines

  1. Start with structure: Define the overall organization before details
  2. Maintain consistent terminology: Use the same terms throughout diagrams
  3. Limit complexity: Keep diagrams focused on one aspect of the system
  4. Use descriptive labels: Make text clear and concise
  5. Validate regularly: Preview changes frequently

Edward Tufte, visualization expert and author of "The Visual Display of Quantitative Information", emphasizes that "clarity in thinking is very much like clarity in the display of data."

Troubleshooting Common Issues

ProblemResolution
Diagram not renderingCheck for syntax errors, especially missing brackets or quotes
Text display issuesVerify special character escaping
Layout problemsAdjust flow direction or reduce complexity
Export errorsRefresh page before attempting export again

The Mermaid GitHub repository provides solutions to common rendering issues.


In Conclusion

Mermaid offers an efficient, text-based approach to diagram creation that integrates seamlessly with documentation processes. Its accessible syntax reduces the learning curve while providing powerful visualization capabilities.

Core Benefits:

  • Version control compatibility: Diagrams can be tracked alongside code
  • Consistency in documentation: Standardized visual language
  • Reduced maintenance overhead: Update diagrams with simple text edits
  • Accessibility: Create diagrams without specialized graphic design tools

According to the 2023 State of DevOps Report by DORA, teams using diagram-as-code approaches like Mermaid are 2.4 times more likely to implement continuous documentation successfully.


Additional Resources

Access the Mermaid diagram tool at tools-online.app/tools/mermaid