File: scatter_with_loess.py

package info (click to toggle)
python-altair 4.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 9,972 kB
  • sloc: python: 22,391; makefile: 222; sh: 14
file content (31 lines) | stat: -rw-r--r-- 755 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
"""
Scatter Plot with LOESS Lines
-----------------------------
This example shows how to add a trend line to a scatter plot using 
the LOESS transform (LOcally Estimated Scatterplot Smoothing).
"""
# category: scatter plots

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

np.random.seed(1)

source = pd.DataFrame({
    'x': np.arange(100),
    'A': np.random.randn(100).cumsum(),
    'B': np.random.randn(100).cumsum(),
    'C': np.random.randn(100).cumsum(),
})

base = alt.Chart(source).mark_circle(opacity=0.5).transform_fold(
    fold=['A', 'B', 'C'], 
    as_=['category', 'y']
).encode(
    alt.X('x:Q'), 
    alt.Y('y:Q'), 
    alt.Color('category:N')
)

base + base.transform_loess('x', 'y', groupby=['category']).mark_line(size=4)