2

I would like to refer to the nth column of a dataframe and use this as input for drawing a graph using altair.
The code looks like this:

#create dataframe
df = pd.DataFrame({'date': ['2020-04-03', '2020-04-04', '2020-04-05', '2020-04-06','2020-04-03', '2020-04-04','2020-04-05','2020-04-06'],
                    'ID': ['a','a','a','a','b','b','b','b'],'bar': [np.nan,8,np.nan,np.nan, np.nan, 8,np.nan,np.nan],
                    'line': [8,np.nan,10,8, 4, 5,6,7] })

#define columns to be used
bb = df.columns[2]
ll = df.columns[3]

#make graph
bars = alt.Chart(df).mark_bar(color="grey", size=5).encode(
         alt.X('monthdate(date):O'), alt.Y(bb))

lines = (alt.Chart(df).mark_line(point=True,size=2)
     .transform_filter('isValid(datum.line)')
     .encode(alt.X('monthdate(date):O'), y='line:Q'))

alt.layer(bars + lines,width=350,height=150).facet(facet=alt.Facet('ID:N'),
    ).resolve_axis(y='independent',x='independent')

I managed for the "bars" part of the graph. But I am not sure how to do this inside the transform_filter function. Instead of specifying the column name "line" I would like to use "ll" or the 3rd column of the dataframe.
Is there a way to do this? Thanks for any help

Aham
  • 113
  • 6

1 Answers1

0

datum is referencing a javascript object, and I don't believe there is any way to access javascript object properties (like line) by index rather than property name. However you could construct the string using Python f-strings which allows you to substitute in the variable value where you need it in the string:

.transform_filter(f'isValid(datum.{ll})')

There is also an expr module in Altair (second example here), but I can't think of a way to use that which is easier than the above.

joelostblom
  • 43,590
  • 17
  • 150
  • 159