7 Building Graphs with full control

The plotly.express module is great for quickly generating exploratory plots. It is relatively powerful but at some point is not always flexible enough for what we need. For example adding multiple layers to our plots, or customised layouts.

For full control over our plotly plots we need to build graphs either from dictionaries or from graph objects.

7.1 Building graphs from dictionaries

The plotly Python package is essentially just a wrapper for a JavaScript library Plotly.js. In the JavaScript library, plots are defined using a declarative JSON data structure. In Python we can build these plots using dictionaries that can be serialized into a JSON data structure. As an example:

best_bond = bond.query('Actor == "Sean Connery"')
fig = {
  'data': [{
    'type': 'scatter',
    'mode': 'markers',
    'x': best_bond['Kills'],
    'y': best_bond['Relationships']
  }],
  'layout': {
    'title': {
      'text': 'A scatter plot'
    }
  }
}

To display a figure defined by a dictionary we can use plotly.io.show()

import plotly.io as pio
pio.show(fig)