arjan-hada
arjan-hada

Reputation: 269

Is there a way to loop and make a plot in Altair?

I am trying to replicate this matplotlib plot in Altair. What would be the best way to do it?

import numpy as np
import matplotlib as plt
N = 10
a = np.random.normal(0, 0.2, size=(N))
b = np.random.normal(1, 0.5, size=(N))
x_seq = np.linspace(-3, 3, 50)

for i in range(N):
  plt.plot(x_seq, a[i] + b[i] * x_seq, "k-", alpha=0.3);

Upvotes: 1

Views: 1210

Answers (1)

joelostblom
joelostblom

Reputation: 48974

Matplotlib has a low level plotting interface that promotes loops operating on arrays (as in your example) whereas packages such as Altair and Seaborn have high level interfaces that work with dataframes and their column names.

So instead of your for loop, you would could do something like this in Altair:

import altair as alt


dfx = pd.DataFrame([a[i] + b[i] * x_seq for i in range(N)]).T
dfx['x'] = x_seq
dfx = dfx.melt(id_vars='x', var_name='line_group', value_name='y')

alt.Chart(dfx).mark_line().encode(
    x='x', 
    y='y',
    color='line_group:N') # N is to explicitly indicate a nominal variable

enter image description here

You can read more about the melting step and why long data is perferred in the docs.

Upvotes: 1

Related Questions