Announcing Dash AG Grid

Plotly
Plotly
Published in
8 min readJan 25, 2023

Written by: Plotly Community Manager, Adam Schroeder, and Plotly CTO and Co-Founder, Alex Johnson

📌 Check out the previously recorded technical tutorial to learn more about this new open-source component library!

Left to right: Adam Schroeder, Alex Johnson
Watch the announcement video to hear from Alex Johnson, Plotly Co-Founder and Chief Technology Officer.

Dash AG Grid is a high-performance and highly customizable component library for working with tabular data that wraps AG Grid. It was initially written as a feature of Dash Enterprise to make this powerful data grid accessible to our customers.

So why are we open-sourcing it?

Over the last few years, Dash AG Grid grew in popularity with more and more of our enterprise customers using it, and community members who had seen or used AG Grid in traditional full-stack web apps asking about using it with their Dash apps. Due to this demand, we are releasing Dash AG Grid to the open-source community! Indeed we’re grateful to have two particularly active community members — Bryan Schroeder and Ann Marie Ward — leading the charge, polishing and improving the component we wrote to make it more powerful, secure, and flexible whether it’s used inside Dash Enterprise or in a fully open-source Dash app.

Check out the open-source repo and start building with pip install dash-ag-grid! (This is an alpha release, so you must use the full version string. The full v2.0.0 release will be in February. Sign up for Plotly’s Dash Club newsletter to get notified.)

What is AG Grid?

AG Grid is a feature-rich data grid designed for enabling you to display and work with tabular data. With 1.2 million downloads per month, this leading component library amplifies the power of tables by offering in-place cell editing, live stream updates, integrated charting, and more.

Features include the ability for users to reorganize grids (column pinning, sizing, and hiding), grouping rows, and nesting grids within another grid’s rows. The company AG Grid focuses entirely on displaying and working with tabular data in the browser, so it is constantly improving.

AG Grid testimonial

Dash AG Grid vs. Dash DataTable

We knew from its earliest days that Dash needed to include tabular data. Of course we love plotting data — it’s right there in the name Plotly! But there’s often no substitute for a good table, particularly if your data has lots of text, or you need to edit, sort, or filter data. Dash DataTable has always been our official answer to that, and we will continue to support it for a long time. If you use Dash DataTable and you like it, great! Keep it up!

However, there are so many things people want to achieve with tabular data. Where Dash DataTable leaves off, Dash AG Grid keeps going: movable, resizable columns, calculated columns, sparklines, and more. And it does it with beautiful, flexible styling, and a modern look.

Like Dash, the core of AG Grid is free and open-source. Also like Dash, AG Grid has an enterprise offering that gives you access to more powerful features — grouping / aggregation with a hierarchical view, pivot tables, and export to excel among others. Dash AG Grid supports both the free “community” version and AG Grid enterprise. To use the enterprise features, all you need is a valid AG Grid license key.

Dash DataTable vs. Dash AG Grid

Step-by-Step Guide

Follow along for a brief step-by-step guide on how to use Dash AG Grid in an app like this one! View the live open-source app and Github code.

Financial portfolio app with Dash AG Grid

This financial portfolio app achieves its powerful interactivity by using the AG Grid table and connecting it with a Candlestick and a pie chart. Let’s view the code used in this article to understand how it’s created.

import dash_ag_grid as dag
from dash import Dash, html, dcc, Input, Output, State
import dash_bootstrap_components as dbc
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import yfinance as yf
app = Dash(__name__, external_stylesheets=[dbc.themes.DARKLY])

First, we import all the libraries used to create the app, then, we instantiate the app and add a dark theme to it. We’ll use the yfinace library to get the stock market data into our app.

equities = {
"AAPL": "Apple",
"MSFT": "Microsoft",
"AMZN": "Amazon",
...
}

def get_stock_data():
return yf.download(tickers=list(equities.keys()),
period="2y", group_by="ticker")

stock_data = get_stock_data()

We create and execute a function that pulls two years of stock market data for eight different companies and saves it to stock_data.

def last_close(ticker):
return stock_data[ticker]["Close"].iloc[-1]

data = {
"ticker": [ticker for ticker in equities],
"company": [name for name in equities.values()],
"quantity": [75, 40, 100, 50, 40, 60, 20, 40],
"price": [last_close(ticker) for ticker in equities],
}

df = pd.DataFrame(data)

This part creates a pandas dataframe with four columns. The first two columns represent the information inside the equities dictionary, created earlier. In the third column we generate fake values for the quantity of shares per company. The fourth column displays the most recent closing price per share. If you print the df, you’ll see more:

columnDefs = [
{
"headerName": "Stock Ticker",
"field": "ticker",
"filter": True,
},
{...},
{...},
]

This columnsDefs list of dictionaries is an important part because further down the app it will be assigned to the AG Grid table to define the columns’ setting.

There are four keys that you will often find in AG Grid. The headerName key is used to set the header title for each column. The field key represents the id of each column. The filter key is used to insert the filter feature, located below the header of each column.

defaultColDef = {
"filter": "agNumberColumnFilter",
"resizable": True,
"sortable": True,
"editable": False,
"floatingFilter": True,
}

The defaultColDef dictionary will be used to define column settings that apply to all columns in the AG Grid table. This will be assigned to the defaultColDef property of the table and can be used instead of the columnDefs property.

For example, if you wanted all columns to be sortable except for one, you would set ”sortable”: True in defaultColDef, and then you would set ”sortable”: False for the one column in columnDefs.

table = dag.AgGrid(
id="portfolio-grid",
className="ag-theme-alpine-dark",
columnDefs=columnDefs,
rowData=df.to_dict("records"),
columnSize="sizeToFit",
defaultColDef=defaultColDef,
dashGridOptions={"undoRedoCellEditing": True, "rowSelection": "single"},
)

The highlight of our app: AG Grid table.

The id will be used later in the callback to help create the interactivity between the table and the graphs.

The className prop is used to declare the theme of the table. Grids can be styled using one of six provided themes from AG Grid: ag-theme-alpine, ag-theme-alpine-dark, ag-theme-balham, ag-theme-balham-dark, ag-theme-material, ag-theme-bootstrap.

The rowData prop is used to assign the data to the table’s rows.

The columnSize prop controls the size of the columns. The sizeToFit string will make the visible columns fit the full available width of the screen. The autoSizeAll string will modify the width of visible columns based on the contents of the cells in each column.

The dashGridOptions property houses many more AG Grid properties that are not as frequently used. The undoRedoCellEditing property allows the user to undo or redo updates to the table. For example, try changing a cell value under the Shares column. Then click CTRL+z on the keyboard to undo that action; then, click CTRL+y to redo that action.

candlestick = dbc.Card(dcc.Graph(id="candlestick"), body=True)
pie = dbc.Card(dcc.Graph(id="asset-allocation"), body=True)
header = html.Div("My Portfolio", className="h2 p-2 text-white bg-primary text-center")

app.layout = dbc.Container(
[
header,
dbc.Row([dbc.Col(candlestick), dbc.Col(pie)]),
dbc.Row(dbc.Col(table, className="py-4")),
],
)

This part of the app builds out the layout, giving you complete control over the location, size, and style of each app component. We define the layout to display the title in the upper part of the page. Right under the title, there will be two cards that will house the candlestick and pie charts. Finally, the AG Grid table is positioned under the charts.

@app.callback(
Output("candlestick", "figure"),
Input("portfolio-grid", "selectionChanged"),
)
def update_candlestick(selected_row):
if selected_row is None:
...
else:
...
fig = go.Figure(...)

return fig

The callback is what generates the powerful interactivity. This part listens to the AG Grid row selected by the user and creates the candlestick chart, based on the company within that row. Try selecting a different row in the app to see how the candlestick chart updates with new stock data.

@app.callback(
Output("asset-allocation", "figure"),
Input("portfolio-grid", "cellValueChanged"),
State("portfolio-grid", "rowData"),
)
def update_portfolio_stats(_, data):
dff = pd.DataFrame(data)
...
return px.pie(...)

The last callback is responsible for the creation of the pie chart that breaks down the percentage and total value of shares held across all companies with the complete portfolio.

The callback is triggered only when a cell value from the table is changed. Once triggered, it will take the complete table data, create a new total value column, build the pie chart, and return it into the figure property of the dcc.Graph to be displayed on the page.

Dash Enterprise + AG Grid

So, what does this mean for Dash Enterprise customers?

If you’re already using Dash AG Grid, you don’t need to change anything. However, to upgrade to the new open-source package, you’ll just need to bump the version number in your requirements.txt file and Python will install it from PyPI, instead of from Dash Enterprise. There are some breaking changes we’ll highlight in the docs and Changelog. All the other features of Dash Enterprise will still supercharge your Dash AG Grid component:

  • Dash Design Kit works seamlessly with Dash AG Grid, so your grid matches the styling of the rest of your app, while you focus on your data, not CSS. Change the style in one place and your whole app reacts together.
  • Dash Snapshot Engine makes Dash AG Grid the star of your reporting system. Improvements we’re making in v2.0.0 — for example more completely capturing the state of user interactions like reordering or resizing columns — make this even more powerful.
  • Dash Embedded seamlessly brings Dash AG Grid — and the rest of your Dash app — into any larger website.

Below is a Dash Enterprise app with AG Grid and Dash Design Kit. Set the style once and all the components (AG Grid, graphs, buttons, and more) get matching colors, fonts, and other elements of style:

Dash Enterprise app with AG Grid and Dash Design Kit
Check out the Dash Enterprise app.

What’s next?

We’re thrilled to share the Dash AG Grid package with the Plotly Community, and we can’t wait to see what you create. Check out the open-source repo and share your apps on our community forum!

Want to see it for yourself? Check out the recorded technical tutorial, featuring Plotly’s CTO and Co-Founder, Alex Johnson. You’ll gain a deeper understanding of Dash AG Grid capabilities, as well as AG Grid Community vs. Enterprise, and how Dash AG Grid applies to Dash Enterprise.

--

--

Plotly
Plotly
Editor for

The low-code framework for rapidly building interactive, scalable data apps in Python.