File: line_with_last_value_labeled.py

package info (click to toggle)
python-altair 5.0.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,952 kB
  • sloc: python: 25,649; sh: 14; makefile: 5
file content (40 lines) | stat: -rw-r--r-- 954 bytes parent folder | download
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
"""
Line Chart with Last Value Labeled
----------------------------------
This chart shows a line chart with a label annotating the final value 
"""
# category: line charts
import altair as alt
from vega_datasets import data

# Import example data
source = data.stocks()

# Create a common chart object
chart = alt.Chart(source).transform_filter(
    alt.datum.symbol != "IBM"  # A reducation of the dataset to clarify our example. Not required.
).encode(
    alt.Color("symbol").legend(None)
)

# Draw the line
line = chart.mark_line().encode(
    x="date:T",
    y="price:Q"
)

# Use the `argmax` aggregate to limit the dataset to the final value
label = chart.encode(
    x='max(date):T',
    y=alt.Y('price:Q').aggregate(argmax='date'),
    text='symbol'
)

# Create a text label
text = label.mark_text(align='left', dx=4)

# Create a circle annotation
circle = label.mark_circle()

# Draw the chart with all the layers combined
line + circle + text