File: layered_heatmap_text.py

package info (click to toggle)
python-altair 5.0.1-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,952 kB
  • sloc: python: 25,649; sh: 14; makefile: 6
file content (42 lines) | stat: -rw-r--r-- 1,001 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"""
Text over a Heatmap
-------------------

An example of a layered chart of text over a heatmap using the cars dataset.
"""
# category: tables
import altair as alt
from vega_datasets import data

source = data.cars()

# Configure common options. We specify the aggregation
# as a transform here so we can reuse it in both layers.
base = alt.Chart(source).transform_aggregate(
    mean_horsepower='mean(Horsepower)',
    groupby=['Origin', 'Cylinders']
).encode(
    alt.X('Cylinders:O'),
    alt.Y('Origin:O'),
)

# Configure heatmap
heatmap = base.mark_rect().encode(
    color=alt.Color('mean_horsepower:Q',
        scale=alt.Scale(scheme='viridis'),
        legend=alt.Legend(title="Mean of Horsepower"),
    )
)

# Configure text
text = base.mark_text(baseline='middle').encode(
    text=alt.Text('mean_horsepower:Q', format=".0f"),
    color=alt.condition(
        alt.datum.mean_horsepower > 150,
        alt.value('black'),
        alt.value('white')
    )
)

# Draw the chart
heatmap + text