File: line_chart_with_custom_legend.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 (40 lines) | stat: -rw-r--r-- 867 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
"""
Line Chart with Custom Legend
-----------------------------
This example uses the argmax aggregation function in order to create a custom
legend for a line chart.
"""
# category: line charts
import altair as alt
from vega_datasets import data


source = data.stocks()

base = alt.Chart(source).encode(
    color=alt.Color("symbol", legend=None)
).transform_filter(
    "datum.symbol !== 'IBM'"
).properties(
    width=500
)

line = base.mark_line().encode(x="date", y="price")


last_price = base.mark_circle().encode(
    x=alt.X("last_date['date']:T"),
    y=alt.Y("last_date['price']:Q")
).transform_aggregate(
    last_date="argmax(date)",
    groupby=["symbol"]
)

company_name = last_price.mark_text(align="left", dx=4).encode(text="symbol")

chart = (line + last_price + company_name).encode(
    x=alt.X(title="date"),
    y=alt.Y(title="price")
)

chart