Skip to content

Chat message with an Altair chart

Mercury chat Message can display interactive charts, tables, and rich outputs. In this example, the assistant responds with an Altair chart based on sales data.

Chat web app with Altair charts created in Python

Try the live web app:

🚀 Load interactive demo Hover to start

In the first notebook cell, import required libraries:

import mercury as mr
import pandas as pd
import altair as alt

We use following aliases:

  • mr for Mercury widgets
  • pandas for data
  • altair for interactive charts

Prepare a simple sales dataset:

sales_df = pd.DataFrame({
"date": ["2023-01-01", "2023-01-08", "2023-01-15", "2023-01-22"],
"region": ["North", "South", "East", "West"],
"product": ["A", "B", "A", "C"],
"units_sold": [10, 15, 7, 12],
"unit_price": [20, 25, 19, 22],
})
sales_df["total_sales"] = sales_df["units_sold"] * sales_df["unit_price"]

Create the Chat widget:

chat = mr.Chat()

In the next cell, create the ChatInput widget:

prompt = mr.ChatInput()

When the user sends a message:

  1. The cell below ChatInput is re-executed
  2. The user message is added to the chat
  3. The assistant creates an Altair chart
  4. The chart is displayed inside the chat message
if prompt.value:
# user message
user_msg = mr.Message(prompt.value, role="user")
chat.add(user_msg)
# assistant message
response_msg = mr.Message(
"**Altair** plot based on sales data",
role="assistant",
emoji="🤖",
)
with response_msg:
# prepare data
df = sales_df.copy()
df["date"] = pd.to_datetime(df["date"])
# create Altair chart
chart = (
alt.Chart(df)
.mark_line(point=True)
.encode(
x=alt.X("date:T", title="Date"),
y=alt.Y("total_sales:Q", title="Total Sales"),
tooltip=["date:T", "total_sales:Q"],
)
.properties(
width=400,
height=250,
title="Total Sales Over Time",
)
)
# display chart in the message
display(chart)
chat.add(response_msg)
  • ChatInput automatically re-runs the cell below it
  • prompt.value contains the latest user message
  • Your code reacts and appends new messages to the chat

No callbacks. No JavaScript. No async code.

  • Altair outputs are HTML-based
  • display(chart) renders directly in the message
  • Charts are interactive (hover tooltips)
  • No need to close figures or manage state