Shapes in Python

How to make SVG shapes in python. Examples of lines, circle, rectangle, and path.


Plotly Studio: Transform any dataset into an interactive data application in minutes with AI. Try Plotly Studio now.

Adding Lines and Polygons to Figures

As a general rule, there are two ways to add shapes (lines or polygons) to figures:

  1. Trace types in the scatter family (e.g. scatter, scatter3d, scattergeo etc) can be drawn with mode="lines" and optionally support a fill="self" attribute, and so can be used to draw open or closed shapes on figures.
  2. Standalone lines, ellipses and rectangles can be added to figures using fig.add_shape(), and they can be positioned absolutely within the figure, or they can be positioned relative to the axes of 2d cartesian subplots i.e. in data coordinates.

Note: there are special methods add_hline, add_vline, add_hrect and add_vrect for the common cases of wanting to draw horizontal or vertical lines or rectangles that are fixed to data coordinates in one axis and absolutely positioned in another.

The differences between these two approaches are that:

  • Traces can optionally support hover labels and can appear in legends.
  • Shapes can be positioned absolutely or relative to data coordinates in 2d cartesian subplots only.
  • Traces cannot be positioned absolutely but can be positioned relative to data coordinates in any subplot type.
  • Traces also support optional text, although there is a textual equivalent to shapes in text annotations.

Shape-drawing with Scatter traces

There are two ways to draw filled shapes: scatter traces and layout.shapes which is mostly useful for the 2d subplots, and defines the shape type to be drawn, and can be rectangle, circle, line, or path (a custom SVG path). You also can use scatterpolar, scattergeo, scattermapbox to draw filled shapes on any kind of subplots. To set an area to be filled with a solid color, you need to define Scatter.fill="toself" that connects the endpoints of the trace into a closed shape. If mode=line (default value), then you need to repeat the initial point of a shape at the end of the sequence to have a closed shape.

In [1]:
import plotly.graph_objects as go

fig = go.Figure(go.Scatter(x=[0,1,2,0], y=[0,2,0,0], fill="toself"))
fig.show()

You can have more shapes either by adding more traces or interrupting the series with None.

In [2]:
import plotly.graph_objects as go

fig = go.Figure(go.Scatter(x=[0,1,2,0,None,3,3,5,5,3], y=[0,2,0,0,None,0.5,1.5,1.5,0.5,0.5], fill="toself"))
fig.show()

Shapes in Dash

Dash is the best way to build analytical apps in Python using Plotly figures. To run the app below, run pip install dash, click "Download" to get the code and run python app.py.