Skip to content

Chat message with a Matplotlib chart

Mercury chat Message can display charts, tables, and rich outputs, not only text. In this example, the assistant responds with a Matplotlib chart based on sales data.

Echo Chat Web App created in Python

You can try the live web app:

🚀 Load interactive demo Hover to start

In the first notebook cell, import Mercury:

import mercury as mr

We will use mr alias to create all widgets.

In the second cell, let’s prepare a simple sales dataset.

import pandas as pd
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"]

Now create the Chat area, it will display all messages.

chat = mr.Chat()

In the next cell, please create the ChatInput to accept user prompts:

prompt = mr.ChatInput()

When the user sends a message:

  1. We add the user message to the chat
  2. We create an assistant message
  3. Inside the message, we draw a Matplotlib chart
  4. The chart is displayed inside the chat bubble
import matplotlib.pyplot as plt
if prompt.value:
# user message
user_msg = mr.Message(prompt.value, role="user")
chat.add(user_msg)
# assistant message
response_msg = mr.Message(
"**Matplotlib** plot based on sales data",
role="assistant",
emoji="🤖",
)
with response_msg:
# create figure
fig, ax = plt.subplots(figsize=(6, 3))
ax.plot(sales_df["date"], sales_df["total_sales"], marker="o")
ax.set_xlabel("Date")
ax.set_ylabel("Total Sales")
ax.set_title("Total Sales Over Time")
fig.tight_layout()
# important: close the figure
plt.close(fig)
# display figure inside the chat message
display(fig)
chat.add(response_msg)
  • Message can display text, markdown, HTML, charts and tables.
  • Everything inside with response_msg: is rendered in the response message.
  • display(fig) shows the Matplotlib figure
  • plt.close(fig) prevents extra empty space and duplicated plots