avatarAmit Kulkarni

Summary

The context provides a comprehensive guide to using Dash AG Grid for creating rich data tables in Plotly Dash, an open-source Python framework for building analytical web applications, comparing it to Dash DataTable, and discussing its benefits and features.

Abstract

The text discusses the use of Dash AG Grid, a powerful library for building complex data tables in Plotly Dash applications, an open-source Python framework. The guide compares Dash AG Grid with Dash DataTable and explores features like sorting, filtering, pagination, and custom formatting. It highlights the benefits of using Dash AG Grid, such as its high performance, enterprise-ready components, and ease of integration with other web technologies. The author emphasizes that AG Grid is a powerful tool for Dash applications and a great option for creating interactive data visualizations. The guide also provides practical steps for installing Dash AG Grid and demonstrates its implementation with code examples and screenshots.

Opinions

  • The author believes that Dash AG Grid is a powerful tool for building complex data tables in Plotly Dash applications, offering enterprise-grade features like filtering, sorting, grouping, and tree data.
  • The author highlights that Dash AG Grid is one of the fastest data grids on the market, making it ideal for large data sets.
  • The author suggests that AG Grid is easily integrated with other web technologies, making it a powerful tool for Dash applications.
  • The author mentions that AG Grid offers features not available in Dash DataTable, such as resizing columns, rearranging columns and rows, and built-in filtering options similar to that of MS Excel.
  • The author implies that AG Grid is a reliable and well-supported tool, ensuring its stability.
  • The author suggests that AG Grid can speed up the development process and help create beautiful and interactive data visualizations.
  • The author clarifies that AG Grid should not replace Dash DataTable but can be used together in the same application depending on the use case.

The Dash AG Grid: A Guide For Creating Rich Data Tables

A much-awaited feature for developing high-performance and highly customizable data grids in Plotly Dash

Source: shubham-dhage | Unsplash

What is Plotly Dash?

Dash is an open-source Python framework used for building analytical web applications and is built on top of Flask, Plotly.js, and React.js. Its simple and easy-to-use framework lets data scientist put their complex model behind the app and the interactive interface enables the users to make business decisions that are backed by data and derived from models.

Need for a framework like Plotly Dash

Many times, data scientists and analysts need to quickly prototype, visualize or build data apps but they might not have the skills of developers or have an understanding of frameworks like Flask or Django. That’s where a lightweight framework like Dash comes into play. If you have used Python for data exploration, analysis, visualization, model building, or reporting then you find it extremely useful for building highly interactive analytic web applications with minimal code.

What is Dash AG Grid?

The Dash AG Grid is the newest addition to the current family of Dash components and widgets. It is an open-source library for building complex data tables with features like sorting, filtering, and pagination. The library is designed for high-performance and large data sets. It is a fully-featured and enterprise-ready grid component that can be used in Dash applications. There is an open-source and also enterprise version(licensed) that has more features.

What is Dash DataTable?

Dash DataTable is an interactive table component designed for viewing, editing, and exploring large datasets. This component was written from scratch in React.js specifically for the Dash community. The Dash DataTable has been a popular choice for representing data in tabular form due to its customizable features like colors, size, formats, and style. It lets users explore data in more depth at the tabular level.

The objective of this blog

In this blog, we will explore the “AG GRID” and how it can be used to build complex data tables. We will compare it with “Dash DataTable and also explore features that make AG Grid a powerful library.

  • How to install Dash AG Grid?
  • Getting started with AG Grid in Dash
  • Dash DataTable Vs Dash AG Grid
  • Benefits of using Dash AG Grid
  • Closing thoughts and references

Project environment

It is always recommended to create a virtual environment for every project.

Virtual environment

We will create a virtual environment for our project and work on it for the rest of the blog. Here are the steps

Step 1: Install the virtual environment if not already done

pip install virtualenv

Step 2: Create a virtual environment by the name eg: venv_AGGRID

virtualenv venv_AGGRID

Step 3: We can switch to venv_AGGRID environment and activate it using the below command.

venv_AGGRID\scripts\activate

Once, the environment is ready, we will install dash-ag-grid and other libraries like Dash, pandas, dash DataTable, etc.

How to install Dash AG Grid and Dash Data Table?

pip install dash-ag-grid==2.0.0a5
pip install dash_table

Loading the libraries

import dash
import pandas as pd
from dash import Dash, html, dcc, dash_table
import dash_ag_grid as dag
import dash_bootstrap_components as dbc

Dash DataTable Vs Dash AG Grid

Let us list all the features that we wish to have on the table and then we will implement these features in both Dash DataTable and AG Grid. We will use the gapminder data in this blog.

  • Rows with alternating colors
  • Ability to select and delete rows
  • Ability to select and delete columns
  • Ability to filter data by a specific column
  • Ability to edit the cell content
  • Custom pagination with easy navigation
  • Custom format for the content of the table
  • Conditional formatting and heatmap

Dash DataTable

  1. Let us start with loading the data. This will be a very bland table with no features or colors. We will improve this in subsequent sections.
import dash
import pandas as pd
from dash import Dash, html, dcc, dash_table
import dash_ag_grid as dag
import dash_bootstrap_components as dbc

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')

app = dash.Dash(__name__)

app.layout = dash_table.DataTable(df.to_dict('records'), [{"name": i, "id": i} for i in df.columns])

if __name__ == "__main__":    
    app.run_server(debug=True, use_reloader=True) 
Source: Author

2. Configure and customize the table to add features like sorting, filtering, pagination, etc.

style_header={
  'backgroundColor': 'rgb(230, 230, 230)',
  'fontWeight': 'bold',

},

style_data={'whiteSpace': 'normal','height': 'auto'},
editable=True,
filter_action="native",
sort_action="native",
sort_mode="multi",
column_selectable="single",
row_selectable="multi",
row_deletable=True,
selected_columns=[],
selected_rows=[],
page_action="native",
page_current= 0,
page_size=10,

3. We have numeric data and it needs to be represented in a standard format (‘ , ’) separated for ease of readability.

"format": {"specifier": ",.2f"}

4. Conditional formatting for column “lifeExp”. Let us say we need to highlight all the cells which are greater than 40 and less than 75. Also, have alternating rows with different shades.

style_data_conditional=[
      {
          'if': {'row_index': 'odd'},
          'backgroundColor': 'rgb(248, 248, 248)'
      },
      {
          'if': {
              'filter_query': '{lifeExp} > 40 && {lifeExp} < 75',
              'column_id': 'lifeExp'
          },
          'backgroundColor': 'tomato',
          'color': 'white'
      },          
  ],

5. let us add the header with the title “Dash DataTable” with the dark background

dbc.Row([
    dbc.Col([
        html.H1("Dash DataTable", 
            style={"text-align": "center", 
                  'font-size': 35, 
                  'font-weight': 'bold', 
                  'color': '#f8f9fa'})
    ])]

6. Run the application

If you have reached this far and faced no errors along the way, the next steps should allow you to run the application.

Step1: Open the terminal, navigate to the project directory

Step 2: Type the below command

<working directory>python app.py

Step 3: The terminal will run the application.

Source: Author

Step 4: Navigate to the browser and type the localhost URL. The app will be loaded as shown below

http:127.0.0.1:8050
Source: Author

You can access the complete from the GitHub

Dash AG Grid

We will be using the same data and the steps for loading data would be the same as that of DataTable (Step 1) from the previous section.

  1. Add the table header
dbc.Row([
   dbc.Col([
        html.H1("Dash AG Grid", 
            style={"text-align": "center", 
                  'font-size': 35, 
                  'font-weight': 'bold', 
                  'color': '#f8f9fa'
            }),
    ])
],

2. Configure editing, sorting, fileting, and resizable feature

defaultColDef={
      "resizable": True, 
      "sortable": True, 
      "filter": True, 
      "editable": True
}
Source: Author

3. Conditional formatting with the criteria (lifeExp > 40 && lifeExp ≤ 75)

getRowStyle1 = {
    "styleConditions": [
        {
            "condition": "params.data.lifeExp > 40 && 
                                  params.data.lifeExp <= 75",
            "style": {"backgroundColor": "lavenderblush"},
        },
    ]
}

4. It will be good to group the columns under separate parent columns eg: The country and continent can be grouped under Region and the remaining columns can be grouped under Quality of life.

{
    "headerName": "Region",
    "children": [
        {"field": "country", "minWidth": 170, "resizable": True, 
            "checkboxSelection": True, "headerCheckboxSelection": True},
        {"field": "continent", "resizable": True},
    ],
},
{
    "headerName": "Quality of Life",
     "children": [
        {"field": "pop"},          
        {"field": "lifeExp"},
        {"field": "gdpPercap"}
     ]
}

5. We should be able to drag and rearrange the columns, select the entire row, make updates, and undo/redo the changes. Also, have pagination to the table.

Please note that except for pagination, all other features were not in our initial list to implement but these are features of AG Grid that are not available in Dash DataTable.

dashGridOptions=
{
    "rowDragManaged": True, 
    'undoRedoCellEditing': True,
    'undoRedoCellEditingLimit': 20,  
    "editType": "fullRow",
    "rowSelection":"single",
    "pagination": True, 
    "paginationAutoPageSize": True,
}

6. We should be able to drag and rearrange the rows similar to that column rearrangement.

columnDefs = [{"field": "country", "rowDrag": True}]
Source: Author

7. Running the application

The process is the same as that of section 6 — “Run the application” from the previous section.

Source: Author

You can access the complete from GitHub.

We built both these grids in a one-page plotly dash application and here is a preview of the application.

Source: Author

Benefits of using Dash AG Grid

AG Grid is a feature-rich data grid that offers enterprise-grade features like filtering, sorting, grouping, and tree data. It is also one of the fastest data grids on the market, making it ideal for large data sets. In addition, AG Grid is easily integrated with other web technologies, making it a powerful tool for Dash applications. There were features that we implemented in AG Grid that were not possible in DataTable like resizing columns, rearranging columns, and rows, and built-in filtering options similar to that of MS Excel.

  • The grid’s features are well suited to the Dash architecture
  • The grid is highly configurable so that you can customize it to your needs
  • The grid is easy to use, so you can get up and running quickly
  • The grid is reliable and well-supported, so you can be confident in its stability

Closing Thoughts

At the end of the day, AG Grid is a powerful tool that can speed up your development process. It is easy to use and easy to integrate into your existing dashboards. If you are looking for a tool to help you create beautiful and interactive data visualizations, AG Grid is a great option.

This doesn’t imply that AG Grid would replace the DataTable. Both can be used together in the same application depending on the use case. We implemented both in a single dash application.

I hope you liked the article and found it helpful.

You can connect with me — on Linkedin and Github

If you liked this blog, here is additional reading on building data apps using Plotly Dash.

References

https://dash.plotly.com/dash-ag-grid

https://github.com/plotly/dash-ag-grid

Unsplash

Ag Grid
Dash Plotly
Visualization
Application Development
Python Programming
Recommended from ReadMedium