Plotly is a powerful data visualization library that allows you to create interactive charts, graphs, and maps. One of the key features of Plotly is the ability to build tables to display tabular data in a visually appealing way.

In this comprehensive guide, we will learn how to create tables using the graph_objects module in Plotly Python.

Overview of Plotly Graph Objects

The graph_objects module contains classes for all the chart types that can be built in Plotly. This includes:

  • Scatter plots
  • Line plots
  • Bar charts
  • Pie charts
  • Tables
  • And more

The graph_objects classes give you fine-grained control over all aspects of a chart from the data to the styling and interactivity.

To create a chart, you initialize an instance of a graph_objects class like Scatter, Bar, or Table and pass in data and styling options.

For example:

import plotly.graph_objects as go

fig = go.Figure(data=[
    go.Bar(y=[2, 5, 1], name=‘First Bar Chart‘) 
])

fig.show()

This creates a simple vertical bar chart using the Bar class.

Now let‘s see how we can use the Table class to build stunning data tables.

Plotly Table Overview

The Table constructor in Plotly accepts a variety of parameters to customize the table. Here are some of the commonly used parameters:

  • header: Sets the column names
  • cells: Sets the cell values displayed in the table
  • columnwidth: Sets the width of columns as a ratio
  • rowheight: Sets the height of rows as a ratio
  • align: Sets alignment of text inside cells (left, center or right)

Additionally, you can style various parts of the table like header, cells, grid lines etc separately using options like:

  • header
  • cells
  • columnwidth
  • line: Styles grid lines

Let‘s now jump into some examples of building tables with sample data sets.

Plotly Table Example 1: Simple Table from Lists

To start with, let us build a simple table by passing list data to header and cells.

import pandas as pd
import plotly.graph_objects as go

headers = ["City", "2010 Population", "2000 Population"]

values = [
    ["New York City, NY", 8175000, 8008000], 
    ["Los Angeles, CA", 3792000, 3694000 ],
    ["Chicago, IL", 2695000 , 2896000]
]

fig = go.Figure(data=[go.Table(
    header=dict(
        values=headers,
        line_color=‘darkslategray‘,
        fill_color=‘royalblue‘,
        font=dict(color=‘white‘, size=14)
    ),
    cells=dict(
        values=values,
        line_color=‘darkslategray‘,
        fill=dict(color=[‘paleturquoise‘, ‘white‘]),
        font=dict(color=‘darkslategray‘, size=12),
        height=30
    ))
])

fig.show()

This generates the following stunning table with custom colors and styled grid lines:

Simple Plotly Table Example

Let‘s break down what‘s happening here:

  • We first create the headers and values lists that contain the textual data
  • Inside the Figure, we add a Table trace and pass header and cells dicts
  • In header, we set blue header fill, white font and gray grid lines
  • For cells, we color alternate rows, set gray font and gray grid lines

And that‘s it! By leveraging the style options, you can create tables with customizable looks and feels.

Next, let us look at building tables from Pandas data frames which is quite common when working with real data sets.

Plotly Table Example 2: Table from Pandas Dataframe

Pandas provides a convenient way to model tabular data and comes with a variety of functions to analyze data sets.

Let‘s see how to convert a Pandas dataframe into an interactive Plotly table.

import pandas as pd
import plotly.graph_objects as go

# Create dataframe
df = pd.DataFrame({
    "Name": ["John", "Mary", "Peter", "Jeff"], 
    "Age": [33, 27, 20, 19],
    "Gender": ["Male", "Female", "Male", "Male"] 
})

# Convert dataframe to plotly table
fig = go.Figure(data=[go.Table(
    header=dict(
        values=list(df.columns),
        font=dict(size=16),
        align="left"
    ),
    cells=dict(
        values=[df.Name, df.Age, df.Gender],
        align = "left"))
])

fig.show()

Here we first create a Pandas dataframe containing some mock data. This includes 3 columns – Name, Age and Gender.

We then convert this dataframe into a Plotly table by:

  • Setting header values to the list of dataframe column names
  • Passing the dataframe columns into cells values
  • Setting alignments and fonts

And this gives us:

Pandas Dataframe to Plotly Table

Pretty cool, right? Pandas + Plotly pair nicely together to create rich data table representations.

Next up, let us explore how to handle large data sets with pagination support.

Plotly Table with Pagination

When dealing with large datasets having thousands of rows, we need to paginate the table for better usability.

Plotly provides a simple pagination option to slice the data displayed in chunks across pages.

Let‘s see an example:

import pandas as pd
import plotly.graph_objects as go

# Create dataframe with 5 pages 
rows = 50
cols = 3
data = [[f"R{r}C{c}" for c in range(cols)] for r in range(rows)]
df = pd.DataFrame(data, columns=[f"Col{c}" for c in range(cols)])

# Initiate figure with page count
fig = go.Figure(data=[go.Table(
    header=dict(
        values=list(df.columns),
        font=dict(size=20), 
        align="left"),
    cells=dict(
        values=[df[col] for col in df.columns],
        align="left"))
    ],
    layout=go.Layout(
        title=‘Full Data Frame‘,
        height=800,
        width=1024,
        showlegend=False,
    ))

# Configure pgination
fig.update_layout(
    updatemenus=[
        dict(
            buttons=list([
                dict(
                    args=["type", "page_current"],
                    label="Current: 1",
                    method="restyle"
                ),
                dict(
                    args=["type", "page_size"],
                    label="Page Size: 25",
                    method="restyle"
                ),
                dict(
                    args=["type", "previous"],
                    label="Previous",
                    method="restyle"
                ),
                dict(
                    args=["type", "next"],
                    label="Next",
                    method="restyle"
                )
            ]),
            direction="left",
            pad={"r": 10, "t": 10},
            showactive=True,
            x=0.11,
            xanchor="left",
            y=1.1,
            yanchor="top"
        ),
    ]
)

# Set initial page size and active button
fig.data[0].page_size= 25
fig.layout.updatemenus[0].buttons[0].args[1] = 0

fig.show()

Here‘s what‘s going on:

  • We use Pandas to generate 50 rows x 3 columns dummy dataset
  • Plotly table trace is created from this dataframe
  • Update layout to show update menus for pagination
  • Menu has options to adjust page size, jump across pages
  • page_size and current page is initialized

When you run the above code, an interactive menu appears on the top right allowing you to paginate across the table:

Plotly Table Pagination

You can use the page size, next and previous buttons to handle large data sets with ease.

Enhancing Plotly Tables with Styling

Since Plotly leverages the power of d3.js internally, you get immense flexibility in styling various parts of a table.

Let‘s see some common style options you can tweak easily:

Header Styling

header=dict(
    values=headers,
    font=dict(size=16, color=‘white‘),
    line=dict(color=‘darkgray‘, width=2),
    fill_color=‘royalblue‘,
    align=‘center‘),
  • font: Sets font size and color
  • line: Controls style of horizontal grid lines
  • fill_color: Header background
  • align: Alignment of text

Cell Styling

cells=dict(
    values=values,
    font=dict(size=14, color=‘darkslategray‘),
    line=dict(color=[‘lightgray‘, ‘white‘]), 
    fill_color=[‘paleturquoise‘, ‘white‘],
    align=[‘left‘, ‘center‘],
    height=30) 
  • line: Customize cell grid lines
  • fill_color: Alternate row coloring
  • align: Alignment per column
  • height: Row height

See this example with live samples of different styling options for deeper understanding.

By mastering various style combinations, you can take your Plotly tables to the next level.

Plotly Tables on Dashboards with Dash

Another excellent use case for Plotly tables is to integrate them into analytical dashboards built with Plotly Dash.

Dash provides a reactive web framework that allows you to easily connect UI elements like tables, charts and controls using Python.

For example, here is a simple dashboard with a drop down to select country, which updates the population Plotly table on selection change:

Interactive Plotly Table Dashboard

Dash + Plotly tables provide a fantastic way to build data apps and BI dashboards rapidly. To learn more, check out Plotly‘s Dash Datatable guide.

Conclusion

Plotly tables provide a versatile way to wrangle, visualize and present tabular data with Python. Using the graph_objects table constructor gives immense control over look, feel, interactivity and pagination of tables.

Pandas integration allows building tables easily from data frames. The styling flexibility helps create modern, aesthetically pleasing tables. And integration into Dash apps helps build full featured GUI analytics apps.

To summarize, key takeaways:

  • Use plotly.graph_objects.Table to generate tables
  • Pass header and cells parameters to supply data
  • Style header, cells, grid etc separately
  • Plotly tables integrate seamlessly with Pandas
  • Build analytical apps with Dash framework

So move beyond boring Excel sheets and CSVs, and start harnessing Plotly tables today for your next data visualization project!

Similar Posts