最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Customizing tooltip font in altair - Stack Overflow

programmeradmin0浏览0评论

I'm using Altair to create an interactive stream graph and want to customize the tooltip font, but I can't figure out how to do it.

I've successfully set fonts in the graph using .configure_axis(), .configure_legend(), and .configure_title(), but these don't cover tooltips, and I can't seem to find directions in the documentation.

Any help would be greatly appreciated!

import altair as alt
import pandas as pd
import numpy as np

# Sample data
np.random.seed(42)
years = list(range(2000, 2020))
destinations = ["USA", "Canada", "Germany", "Australia", "UK"]
data = []

for year in years:
    for dest in destinations:
        data.append({"year": year, "destination": dest, "value": np.random.randint(1000, 10000)})

# Create the DF
flow_data_aggregated = pd.DataFrame(data)

# Create the interactive selection
selection = alt.selection_multi(fields=["destination"], bind="legend", toggle=True)

# Create the graph
stream_graph = alt.Chart(flow_data_aggregated).mark_area(
    interpolate="basis",
    opacity=0.85
).encode(
    x=alt.X("year:O", title="Year", axis=alt.Axis(ticks=False, labelAngle=0, domain=False, grid=False)),
    y=alt.Y("value:Q", stack="center", title="Population Size", axis=None),
    color=alt.Color("destination:N", legend=alt.Legend(title="Destination")),  # No scale → Uses default colors
    opacity=alt.condition(selection, alt.value(1), alt.value(0.1)),
    tooltip=[
        alt.Tooltip("year:O", title="Year"),
        alt.Tooltip("destination:N", title="Country"),
        alt.Tooltip("value:Q", title="Pop Size", format=",.0f")
    ]
).add_selection(selection).properties(
    width=1000,
    height=500,
    title="",
    background="white"
).configure_view(
    strokeWidth=0
).configure_axis(
    labelFont="Merriweather",
    labelFontSize=12,
    titleFont="Merriweather",
    titleFontSize=14,
    gridColor="lightgray"
).configure_legend(
    labelFont="Merriweather",
    labelFontSize=12,
    titleFont="Merriweather",
    titleFontSize=14,
    orient="bottom",
    direction="horizontal"
).configure_title(
    font="Merriweather",
    fontSize=16,
    color="darkblue",
    anchor="middle"
).interactive()

# Save as HTML
html_filename = "stream_graph_example.html"
stream_graph.save(html_filename)
发布评论

评论列表(0)

  1. 暂无评论