README.md
以下内容由 AI 翻译,如有问题请点此提交 issue 反馈
fh-altair
让在 FastHTML 中展示使用 altair 创建的 vegalite 图表变得更加简单。
使用方法
您可以通过运行以下命令来安装此工具:
python -m pip install fh-altair
完成此步骤后,它即可投入使用!要使用它,您需要确保在您的 FastHTML 应用中添加正确的标题。
from fh_altair import altair_headers
app, rt = fast_app(
hdrs = altair_headers
)
这样就能确保所需的 JavaScript 和 CSS 文件始终被加载。接下来您只需将您的 Altair 图表用我们的函数包裹起来,即可正常使用了!
from fh_altair import altair2fasthtml
def generate_chart():
pltr = pd.DataFrame({'y': [1, 2, 3, 2], 'x': [3, 1, 2, 4]})
chart = alt.Chart(pltr).mark_line().encode(x='x', y='y').properties(width=400, height=200)
return altair2fasthtml(chart)
这将返回一个包含已渲染的 Altair 图表的 Div。
自定义 Vega 选项
在底层,altair2fasthtml 会调用 vegaEmbed JavaScript 库。该 vegaEmbed JavaScript 库支持多种可修改渲染后图表外观的选项。您也可以选择传递自定义的 Vega 选项,方式如下:
# To render your chart as a svg instead of the default canvas element
altair2fasthtml(chart, vega_options={"renderer":"svg"})
# To render your chart with action links turned on (by default action links are disabled)
altair2fasthtml(chart, vega_options={"actions":True})
响应式宽度
如上面的示例代码所示,您可以使用 alt.Chart(...).properties(width, height) 来控制图表的宽度和高度。此外,如果您希望图表能够动态占据其父容器的全部宽度,可以像这样将 full_width=True 传递给 altair2fasthtml:
# Renders a chart taking up the full width of the parent container
altair2fasthtml(chart, full_width=True)
发展路线图
这个仓库最初只是作为一个简单的辅助工具,但如果出现更高级的用例,我也很乐意加以考虑。不过在提交 Pull Request 之前,请先通过创建 issue 来展开讨论。