ChartWidget API¶
ChartWidget(widget_id=None)
¶
Bases: BaseWidget
, ChartMixin
Embed charts in emails, supporting matplotlib
and seaborn
.
This widget can seamlessly embed dynamically generated charts (such as matplotlib
or seaborn
chart objects)
or static image files (local or URL) into email content. It automatically handles chart
rendering, Base64 encoding, and Chinese character display issues, greatly facilitating the creation of data visualization reports.
Core features
- Dynamic chart support: Directly accepts
matplotlib.pyplot
orseaborn
chart objects. - Static image support: Can load images through URL or local file paths.
- Automatic Chinese fonts: Automatically detects and configures appropriate Chinese fonts to ensure normal display of Chinese text in charts.
- Content enhancement: Supports adding titles, descriptions, and data summaries to charts.
Examples:
Use matplotlib
to create a simple bar chart and add it to an email:
import matplotlib.pyplot as plt
from email_widget.widgets import ChartWidget
# 1. Create a matplotlib chart
plt.figure(figsize=(10, 6))
categories = ['Q1', 'Q2', 'Q3', 'Q4']
sales = [120, 150, 130, 180]
plt.bar(categories, sales, color='skyblue')
plt.title('Annual Sales (10k Yuan)')
plt.ylabel('Sales')
# 2. Create ChartWidget and set chart
chart = (ChartWidget() .set_chart(plt) # Pass plt object
.set_title("2024 Annual Sales Performance") .set_description("Quarterly sales comparison chart showing annual sales trends.") .set_data_summary("Total Sales: 5.8 million yuan, Highest Quarter: Q4"))
# Assuming email is an Email object
# email.add_widget(chart)
Using external image URL:
chart_from_url = (ChartWidget() .set_image_url("https://www.example.com/charts/monthly_trends.png") .set_title("Monthly Trend Chart") .set_alt_text("A line chart showing monthly growth trends"))
Initialize ChartWidget.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
widget_id
|
Optional[str]
|
Optional Widget ID. |
None
|
Functions¶
get_template_context()
¶
Get context data required for template rendering
set_alt_text(alt)
¶
Set image alternative text.
Used for accessibility and when image loading fails.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
alt
|
str
|
Alternative text. |
required |
Returns:
Name | Type | Description |
---|---|---|
ChartWidget |
ChartWidget
|
Returns self to support method chaining. |
Examples:
set_chart(plt_obj)
¶
Set matplotlib/seaborn chart object.
Convert chart object to Base64-encoded PNG image embedded in email. Automatically configure Chinese font support.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
plt_obj
|
Any
|
matplotlib pyplot object or figure object. |
required |
Returns:
Name | Type | Description |
---|---|---|
ChartWidget |
ChartWidget
|
Returns self to support method chaining. |
Raises:
Type | Description |
---|---|
ImportError
|
If matplotlib library is not installed. |
Exception
|
If chart conversion fails. |
Examples:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(10, 6))
ax.bar(['Q1', 'Q2', 'Q3', 'Q4'], [100, 120, 140, 110])
ax.set_title('Quarterly Sales')
chart = ChartWidget().set_chart(plt)
# Using seaborn
import seaborn as sns
sns.barplot(data=df, x='month', y='sales')
chart = ChartWidget().set_chart(plt)
Note
After calling this method, the original chart object will be closed to free memory. If conversion fails, the image URL will be set to None.
set_data_summary(summary)
¶
Set data summary.
Display key data summary information below the chart.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
summary
|
str
|
Data summary text. |
required |
Returns:
Name | Type | Description |
---|---|---|
ChartWidget |
ChartWidget
|
Returns self to support method chaining. |
Examples:
set_description(description)
¶
Set chart description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
description
|
str
|
Chart description text. |
required |
Returns:
Name | Type | Description |
---|---|---|
ChartWidget |
ChartWidget
|
Returns self to support method chaining. |
Examples:
set_image_url(image_url, cache=True)
¶
Set chart image URL or file path.
This method supports loading images from network URLs or local file paths. Images are automatically processed and converted to Base64-encoded data URIs, directly embedded into HTML to ensure compatibility in email clients.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
image_url
|
Union[str, Path]
|
Image URL string or local file Path object. |
required |
cache
|
bool
|
Whether to cache network images, defaults to True. |
True
|
Returns:
Name | Type | Description |
---|---|---|
ChartWidget |
ChartWidget
|
Returns self to support method chaining. |
Raises:
Type | Description |
---|---|
ValueError
|
If image URL or path is invalid, or image processing fails. |
Examples:
set_max_width(max_width)
¶
Set maximum width of chart container.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
max_width
|
str
|
CSS maximum width value. |
required |
Returns:
Name | Type | Description |
---|---|---|
ChartWidget |
ChartWidget
|
Returns self to support method chaining. |
Examples:
set_title(title)
¶
Set chart title.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title
|
str
|
Chart title text. |
required |
Returns:
Name | Type | Description |
---|---|---|
ChartWidget |
ChartWidget
|
Returns self to support method chaining. |
Examples: