Graphing mathematical functions with Altair

Altair is a python graphing package by Jake VanderPlas. Let's give it a try.


In [1]:
import altair as alt
import pandas as pd
import numpy as np

Line


In [30]:
x = np.arange(-10, 11, 1)
y = 2 * x + 3

In [31]:
y


Out[31]:
array([-17, -15, -13, -11,  -9,  -7,  -5,  -3,  -1,   1,   3,   5,   7,
         9,  11,  13,  15,  17,  19,  21,  23])

In [32]:
source = pd.DataFrame({
  'x': x,
  'y': y
})

In [33]:
source


Out[33]:
x y
0 -10 -17
1 -9 -15
2 -8 -13
3 -7 -11
4 -6 -9
5 -5 -7
6 -4 -5
7 -3 -3
8 -2 -1
9 -1 1
10 0 3
11 1 5
12 2 7
13 3 9
14 4 11
15 5 13
16 6 15
17 7 17
18 8 19
19 9 21
20 10 23

In [34]:
alt.Chart(source).mark_line(point=True, clip=True).encode(
    alt.X('x',
        scale=alt.Scale(domain=(-20, 20))
    ),
    y='y'
)


Out[34]:

Parabola


In [180]:
x = np.arange(-10, 11, 1)
y = x**2

In [181]:
source = pd.DataFrame({
  'x': x,
  'y': y
})

In [182]:
alt.Chart(source).mark_line(point=True).encode(
    x=alt.X('x'),
    y='y'
)


Out[182]:

Square root


In [67]:
x = np.arange(0, 26, 0.1)
y = np.sqrt(x)

In [68]:
source = pd.DataFrame({
  'x': x,
  'y': y
})

In [76]:
a = alt.Chart(source).mark_line(point=True).encode(
    x=alt.X('x'),
    y='y'
)
a.properties(height=500, width=700)


Out[76]:

Circle


In [ ]:
r = 10
i = 0.1
x1 = np.arange(-10, 10.1, i)
x2 = np.arange(10, -10.1, -i)

y1 = np.sqrt(r**2 - x1**2)
y2 = -np.sqrt(r**2 - x2**2)

x = np.concatenate((x1, x2))
y = np.concatenate((y1, y2))

In [128]:
source = pd.DataFrame({
  'x': x,
  'y': y
})

In [129]:
source


Out[129]:
x y
0 -10.0 0.000000
1 -9.9 1.410674
2 -9.8 1.989975
3 -9.7 2.431049
4 -9.6 2.800000
... ... ...
397 -9.6 -2.800000
398 -9.7 -2.431049
399 -9.8 -1.989975
400 -9.9 -1.410674
401 -10.0 -0.000001

402 rows × 2 columns


In [130]:
a = alt.Chart(source).mark_line(point=True).encode(
    alt.X('x',
        scale=alt.Scale(domain=(-12, 12)),
        sort=[False],
    ),
    alt.Y('y',
        scale=alt.Scale(domain=(-12, 12)),
    ),
)
a.properties(height=500, width=520)


Out[130]:

In [ ]: