Search code examples
pythonplotlysubplotfacet-grid

How can we make a faceted grid in subplots in Plotly?


How can we make a faceted grid in subplots in Plotly? For example I want to plot the total_bill versus tip five times in subplots. I tired to do the following:

import plotly.plotly as py
import plotly.figure_factory as ff
from plotly import tools

subfigs = tools.make_subplots(rows= 5, cols=1)

import pandas as pd
tips = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv')

for i in enumerate(tips.columns.tolist()):
    fig = ff.create_facet_grid(
    tips,
    x='total_bill',
    y='tip',
    color_name='sex',
    show_boxes=False,
    marker={'size': 10, 'opacity': 1.0},
    colormap={'Male': 'rgb(165, 242, 242)', 'Female': 'rgb(253, 174, 216)'}
    )

    subfigs.append_trace(fig, i+1, 1)

pyo.iplot(fig)

This does not work, because the faceted grid created by the figure factory is not considered as trace. Is there a way of doing this? This answer did not help because as it seemed to me cufflinks does not accept faceted grids


Solution

  • There are a number of things going on in here.

    1. The function enumerate in python gives you a list of tuples, if you want to iterate by just the indexes you can use

      for i in range(tips.columns.size):
      

      otherwise you can unpack by doing

      for i, col in enumerate(tips.columns):
      
    2. The methods from figure factory return Figures, which contain Traces in it's data list. You can access one of the traces produced by the create_facet_grid method by it's index:

      subfig.append_trace(fig['data'][index_of_the_trace], n1, n2)
      
    3. The idea of faceted grids is to split the dataset by one of it's categoric columns, here's an example of how you can assign the partitions of the dataset by some selected column to different subplots:

      tips = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv')
      
      current_column = 'sex'
      
      subfigs = tools.make_subplots(
          rows = tips[current_column].nunique(),
          cols = 1
      )
      
      fig = ff.create_facet_grid(
          tips,
          x = 'total_bill',
          y = 'tip',
          facet_row  = current_column,
          color_name = 'sex',
          show_boxes = False,
          marker     = {'size': 10, 'opacity': 1.0},
          colormap   = {
              'Male': 'rgb(165, 242, 242)',
              'Female': 'rgb(253, 174, 216)'
          }
      )
      
      for i in range(tips[current_column].nunique()):
          subfigs.append_trace(fig['data'][i], i+1, 1)
      
      py.iplot(fig)
      

    hope it helps.