跳转至

ChartWidget API

ChartWidget(widget_id=None)

Bases: BaseWidget, ChartMixin

在邮件中嵌入图表,支持 matplotlibseaborn.

该微件能够将动态生成的图表(如 matplotlibseaborn 的图表对象) 或静态的图片文件(本地或URL)无缝嵌入到邮件内容中.它会自动处理图表的 渲染、Base64 编码以及中文字符的显示问题,极大地方便了数据可视化报告的创建.

核心功能
  • 动态图表支持: 直接接受 matplotlib.pyplotseaborn 的图表对象.
  • 静态图片支持: 可通过 URL 或本地文件路径加载图片.
  • 自动中文字体: 自动检测并配置合适的中文字体,确保图表中的中文正常显示.
  • 内容增强: 支持为图表添加标题、描述和数据摘要.

Examples:

使用 matplotlib 创建一个简单的柱状图并添加到邮件中:

Python
import matplotlib.pyplot as plt
from email_widget.widgets import ChartWidget

# 1. 创建一个 matplotlib 图表
plt.figure(figsize=(10, 6))
categories = ['第一季度', '第二季度', '第三季度', '第四季度']
sales = [120, 150, 130, 180]
plt.bar(categories, sales, color='skyblue')
plt.title('年度销售额(万元)')
plt.ylabel('销售额')

# 2. 创建 ChartWidget 并设置图表
chart = (ChartWidget()                 .set_chart(plt)  # 将 plt 对象传入
         .set_title("2024年度销售业绩")                 .set_description("各季度销售额对比图,展示了全年的销售趋势.")                 .set_data_summary("总销售额: 580万元, 最高季度: 第四季度"))

# 假设 email 是一个 Email 对象
# email.add_widget(chart)

使用外部图片URL:

Python
chart_from_url = (ChartWidget()                          .set_image_url("https://www.example.com/charts/monthly_trends.png")                          .set_title("月度趋势图")                          .set_alt_text("一张显示月度增长趋势的折线图"))

初始化ChartWidget.

Parameters:

Name Type Description Default
widget_id Optional[str]

可选的Widget ID.

None

Functions

get_template_context()

获取模板渲染所需的上下文数据

set_alt_text(alt)

设置图片的替代文本.

用于无障碍访问和图片加载失败时显示.

Parameters:

Name Type Description Default
alt str

替代文本.

required

Returns:

Name Type Description
ChartWidget ChartWidget

返回self以支持链式调用.

Examples:

Python Console Session
>>> chart = ChartWidget().set_alt_text("销售数据柱状图")
set_chart(plt_obj)

设置matplotlib/seaborn图表对象.

将图表对象转换为Base64编码的PNG图片嵌入到邮件中. 自动配置中文字体支持.

Parameters:

Name Type Description Default
plt_obj Any

matplotlib的pyplot对象或figure对象.

required

Returns:

Name Type Description
ChartWidget ChartWidget

返回self以支持链式调用.

Raises:

Type Description
ImportError

如果未安装matplotlib库.

Exception

如果图表转换失败.

Examples:

Python
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('季度销售额')
chart = ChartWidget().set_chart(plt)

# 使用seaborn
import seaborn as sns
sns.barplot(data=df, x='month', y='sales')
chart = ChartWidget().set_chart(plt)
Note

调用此方法后,原图表对象会被关闭以释放内存. 如果转换失败,图片URL会被设置为None.

set_data_summary(summary)

设置数据摘要.

在图表下方显示关键数据摘要信息.

Parameters:

Name Type Description Default
summary str

数据摘要文本.

required

Returns:

Name Type Description
ChartWidget ChartWidget

返回self以支持链式调用.

Examples:

Python Console Session
>>> chart = ChartWidget().set_data_summary("平均增长率: 15.3%, 最高值: ¥50万")
set_description(description)

设置图表描述.

Parameters:

Name Type Description Default
description str

图表描述文本.

required

Returns:

Name Type Description
ChartWidget ChartWidget

返回self以支持链式调用.

Examples:

Python Console Session
>>> chart = ChartWidget().set_description("展示了各地区的销售对比情况")
set_image_url(image_url, cache=True)

设置图表图片URL或文件路径.

此方法支持从网络URL或本地文件路径加载图片.图片会被自动处理并转换为 Base64编码的data URI,直接嵌入到HTML中,以确保在邮件客户端中的兼容性.

Parameters:

Name Type Description Default
image_url Union[str, Path]

图片的URL字符串或本地文件Path对象.

required
cache bool

是否缓存网络图片,默认为True.

True

Returns:

Name Type Description
ChartWidget ChartWidget

返回self以支持链式调用.

Raises:

Type Description
ValueError

如果图片URL或路径无效,或图片处理失败.

Examples:

Python Console Session
>>> # 使用URL
>>> chart = ChartWidget().set_image_url("https://example.com/chart.png")
Python Console Session
>>> # 使用本地文件路径
>>> from pathlib import Path
>>> chart = ChartWidget().set_image_url(Path("./charts/sales.png"))
set_max_width(max_width)

设置图表容器的最大宽度.

Parameters:

Name Type Description Default
max_width str

CSS最大宽度值.

required

Returns:

Name Type Description
ChartWidget ChartWidget

返回self以支持链式调用.

Examples:

Python Console Session
>>> chart = ChartWidget().set_max_width("800px")
>>> chart = ChartWidget().set_max_width("90%")
set_title(title)

设置图表标题.

Parameters:

Name Type Description Default
title str

图表标题文本.

required

Returns:

Name Type Description
ChartWidget ChartWidget

返回self以支持链式调用.

Examples:

Python Console Session
>>> chart = ChartWidget().set_title("2024年销售趋势")