Download notebook (.ipynb)

geom_function()#

import pandas as pd
from scipy.stats import norm

from lets_plot import *
LetsPlot.setup_html()
ggplot() + geom_function(fun=norm.pdf, xlim=[-3, 3])

1. Comparison With Empirical Density#

df = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv")

xs = df["cty"]

loc, scale = xs.mean(), xs.std()
xmin, xmax = xs.min(), xs.max()

fun = lambda t: norm.pdf(t, loc, scale)
ggplot(df, aes("cty")) + \
    geom_density() + \
    geom_function(fun=fun, xlim=[xmin, xmax], color="red")

2. Use Data to Autodetect xlim#

ggplot(df, aes("cty")) + \
    geom_density() + \
    geom_function(aes("cty"), data=df, fun=fun, color="red")

3. Composition of Function and Statistic#

ggplot(df, aes("cty")) + \
    geom_density() + \
    geom_function(fun=fun, xlim=[xmin, xmax], \
                  stat='smooth', method='loess', span=.3, color="red")

4. Use Different Geometry#

ggplot(df, aes("cty")) + \
    geom_density() + \
    geom_function(aes(fill='y'), fun=fun, xlim=[xmin, xmax], n=30, \
                  geom='histogram', alpha=.5) + \
    scale_fill_brewer(type='seq', palette='YlOrRd', trans='reverse')