Creating diagrams in Sphinx

Using Graphviz

Besides using raster images (PNG, JPG, etc.), diagrams can be included with the `sphinx.ext.graphviz`_ extension.

Graphviz_ is an open source graph visualisation software. Graph visualisation is a way of representing structural information as diagrams of abstract graphs and networks.

It must be installed before the extension can be used.

Due to current (2013.10) compatibility issues with PlantUML, it may be preferable to install GraphViz 2.28 instead.

Including the extension in the project configuration file

The Graphviz extension is included with Sphinx, but the extension must be enabled in the conf.py file:

extensions = ['sphinx.ext.graphviz']

Changing the configuration file

Extensions local to a project should be put within the project’s directory structure. Set Python’s module search path, sys.path, accordingly so that Sphinx can find them. E.g., if your extension foo.py lies in the exts subdirectory of the project root, put into conf.py:

import sys, os
sys.path.append(os.path.abspath('exts'))
extensions = ['foo']

You can also install extensions anywhere else on sys.path, e.g. in the site-packages directory.

Examples

This code:

.. graphviz::

   digraph {
      "From" -> "To";
   }

has this result:

digraph {
   "From" -> "To";
}

This code:

.. graphviz::

   digraph Flatland {
   
      a -> b -> c -> g; 
      a  [shape=polygon,sides=4]
      b  [shape=polygon,sides=5]
      c  [shape=polygon,sides=6]
   
      g [peripheries=3,color=yellow];
      s [shape=invtriangle,peripheries=1,color=red,style=filled];
      w  [shape=triangle,peripheries=1,color=blue,style=filled];
      
      }

has this result:

digraph Flatland {

   a -> b -> c -> g;
   a  [shape=polygon,sides=4]
   b  [shape=polygon,sides=5]
   c  [shape=polygon,sides=6]

   g [peripheries=3,color=yellow];
   s [shape=invtriangle,peripheries=1,color=red,style=filled];
   w  [shape=triangle,peripheries=1,color=blue,style=filled];

   }

Numerous examples are available online:

Using PlantUML

The `Sphinx PlantUML extension`_ (in this case a contributed extension) allows Sphinx to embed UML diagrams by using PlantUML.

PlantUML_ is a Java component that allows to quickly write simple UML diagrams:

  • use case diagrams,
  • class diagrams,
  • activity diagrams,
  • state diagrams,
  • component diagrams,
  • sequence diagrams,
  • object diagram.

Diagrams are defined using a simple and intuitive language. This can be used within many other tools. Images can be generated in PNG or SVG format.

Installing the extension

The module is installed with the following command:

pip install sphinxcontrib-plantuml

Including the extension in the project configuration file

The extension must be enabled in the conf.py file:

extensions = ['sphinxcontrib.plantuml']

The path to the PlantUML file may have to be specified (assuming that Java itself is already in the search path):

plantuml = 'java -jar ../utils/plantum.jar'

PlantUML requires Graphviz and an environment variable may have to be defined, pointing to the dot executable. For example (in Linux or OS-X):

setenv GRAPHVIZ_DOT /usr/local/bin/graphviz/dot
export GRAPHVIZ_DOT

Note

For Ubuntu users

Files with the .sh extension in the /etc/profile.d directory get executed whenever a bash login shell is entered (e.g. when logging in from the console or over ssh), as well as by the DisplayManager when the desktop session loads:

/etc/profile.d/*.sh

You can for instance create the file /etc/profile.d/myenvvars.sh and set variables like this:

export GRAPHVIZ_DOT=/usr/bin/dot

Note

For Windows users

Regardless of the existence of the GRAPHVIZ_DOT environment variable, the path to the Graphviz bin folder is apparently required to be in the PATH variable as well.

Examples

In the Sphinx reST documents, simply begin the PlantUML code with the uml directive.

This is the code for the example above:

.. uml:: 
   
   @startuml
   user -> (use PlantUML)

   note left of user
      Hello!   
   end note
   @enduml

Another example:

This is the code for the example above:

.. uml::
   
   @startuml 
   Alice -> Bob: Hi!
   Alice <- Bob: How are you?
   @enduml

Class diagram

Diagram

This is the diagram generated by the Sphinx PlantUML extension.

Code

This is the code for example above.

.. uml::

      @startuml
      
      'style options 
      skinparam monochrome true
      skinparam circledCharacterRadius 0
      skinparam circledCharacterFontSize 0
      skinparam classAttributeIconSize 0
      hide empty members
      
      Class01 <|-- Class02
      Class03 *-- Class04
      Class05 o-- Class06
      Class07 .. Class08
      Class09 -- Class10
      
      @enduml

Note that in docutils / Sphinx, @startuml and @enduml could be omitted. However, it is useful to keep these lines: is necessary, PlantUML can be used (outside Sphinx) to generate the PNG image files with the diagrams directly from the text file; also, if editing the code in Eclipse, the PlantUML diagrams can be previewed without the necessity of building the documentation.

Image

The image was exported using the Eclipse PlantUML plug-in. It it static, but can be resized...

../_images/classDiagram-Relations.png

Other examples

.. uml::

      @startuml
      
      'style options 
      skinparam monochrome true
      skinparam circledCharacterRadius 0
      skinparam circledCharacterFontSize 0
      skinparam classAttributeIconSize 0
      hide empty members
      
      class Car
      
      Driver - Car : drives >
      Car *- Wheel : have 4 >
      Car -- Person : < owns
      
      @enduml

To declare fields and methods, you can use the symbol ”:” followed by the field’s or method’s name. The system checks for parenthesis to choose between methods and fields.

.. uml::

      @startuml
      
      'style options 
      skinparam monochrome true
      skinparam circledCharacterRadius 9
      skinparam circledCharacterFontSize 8
      skinparam classAttributeIconSize 0
      hide empty members

      abstract class AbstractClass {
        - privateField
        + publicField
        # protectedField
        ~ packagePrivateField
        - privateMethod()
        + publicMethod()
        # protectedMethod()
        ~ packagePrivateMethod()
         }
  
      class Dummy {
        {static} staticID
        {abstract} void methods()
         }
      
      class Flight {
         flightNumber : Integer
         departureTime : Date
         }
      
      package "Classic Collections" {
         
         abstract class AbstractList
         abstract AbstractCollection
         interface List
         interface Collection
         
         List <|-- AbstractList
         Collection <|-- AbstractCollection
         
         Collection <|- List
         AbstractCollection <|- AbstractList
         AbstractList <|-- ArrayList
         
         class ArrayList {
           Object[] elementData
           size()
            } 
      }
      
      enum TimeUnit {
        DAYS
        HOURS
        MINUTES
      }
        

      class Student {
        Name
      }
      Student "0..*" -- "1..*" Course
      (Student, Course) .. Enrollment
      
      class Enrollment {
        drop()
        cancel()
      }

      @enduml

Use case diagram

Code

Diagram

This is generated by the Sphinx PlantUML extension.

Code

.. uml::

   @startuml
   actor "Main Database" as DB << Application >>
   
   note left of DB
      This actor 
      has a "name with spaces",
      an alias
      and a stereotype 
   end note
   
   actor User << Human >>
   actor SpecialisedUser
   actor Administrator
   
   User <|--- SpecialisedUser
   User <|--- Administrator
   
   usecase (Use the application) as (Use) << Main >>
   usecase (Configure the application) as (Config)
   Use ..> Config : <<includes>>
   
   User --> Use
   DB --> Use
   
   Administrator --> Config 
   
   note "This note applies to\nboth actors." as MyNote
   MyNote .. Administrator
   MyNote .. SpecialisedUser
   
   '  this is a text comment and won't be displayed
   AnotherActor ---> (AnotherUseCase)
   
   '  to increase the length of the edges, just add extras dashes, like this:
   ThirdActor ----> (LowerCase)
   
   '  The direction of the edge can also be reversed, like this:
   (UpperCase) <---- FourthActor
   
   @enduml

Image

The image was exported using the Eclipse PlantUML plug-in. It it static, but can be resized...

../_images/useCaseDiagram.png

Activity diagram (new syntax)

Diagram

Code

There are two syntaxes to create activity diagrams. The example utilises the new syntax (which is still incomplete).

.. uml::

   @startuml
   
   start
   
   :first activity;
   
   :second activity
    with a multiline 
    and rather long description;
   
   :another activity;
   
   note right
     After this activity,
     are two 'if-then-else' examples. 
   end note
   
   if (do optional activity?) then (yes)
      :optional activity;
   else (no)
   
      if (want to exit?) then (right now!)
         stop
      else (not really)
      
      endif
   
   endif   
      
   :third activity;
   
   note left
     After this activity,
     parallel activities will occur. 
   end note
   
   fork
      :Concurrent activity A;
   fork again
      :Concurrent activity B1;
      :Concurrent activity B2;
   fork again
      :Concurrent activity C;
      fork
      :Nested C1;
      fork again
      :Nested C2;
      end fork
   end fork
   
   repeat 
      :repetitive activity;
   repeat while (again?)
   
   while (continue?) is (yes, of course)
     :first activity inside the while loop;
     :second activity inside the while loop;
   endwhile (no)
   
   stop
   
   @enduml

Image

The image was exported using the Eclipse PlantUML plug-in. It it static, but can be resized...

../_images/activityDiagram.png

State diagram

Diagram

Generated by the Sphinx PlantUML extension.

Code

.. uml::

   @startuml
   
   [*] --> MyState
   MyState --> CompositeState
   MyState --> AnotherCompositeState
   MyState --> WrongState
   
   CompositeState --> CompositeState : \ this is a loop   
   AnotherCompositeState --> [*]
   CompositeState --> [*]
   
   MyState : this is a string
   MyState : this is another string
   
   state CompositeState {
   
   [*] --> StateA : begin something
   StateA --> StateB : from A to B
   StateB --> StateA : from B back to A
   StateB --> [*] : end it

   CompositeState : yet another string
   }

   state AnotherCompositeState {
   
   [*] --> ConcurrentStateA    
   ConcurrentStateA --> ConcurrentStateA 
   
   --
   
   [*] --> ConcurrentStateB
   ConcurrentStateB --> ConcurrentStateC
   ConcurrentStateC --> ConcurrentStateB
   }
      
   note left of WrongState
      This state 
      is a dead-end
      and shouldn't
      exist.
   end note
   
   @enduml

Image

The image was exported using the Eclipse PlantUML plug-in. It it static, but can be resized...

../_images/stateDiagram.png

GUI mockups

PlantUML can also be used for GUI mockups (see http://plantuml.sourceforge.net/salt.html).

Example

Code

.. uml::

   @startuml
   salt
   {
     Just plain text
     [This is my button]
     ()  Unchecked radio
     (X) Checked radio
     []  Unchecked box
     [X] Checked box
     "Enter text here   "
     ^This is a droplist^
   }
   @enduml