Reputation: 392
The situation seems to be quite simple: I am working in a Jupyter Lab file with several Altair plots, which eventually make the file too large to run and to save. Since I don't need to see these plots every single time, I figured I could avoid this by specifying something like plotAltair = True
at the beginning of the script and then nesting each Altair plot in if
statements. As simple as this may sound, for some reason it doesn't appear to work. Am I missing out on something obvious? [edit: turns out I was]
For instance:
import altair as alt
import os
import pandas as pd
import numpy as np
lengths = np.random.randint(0,100,200)
lengths_list = lengths.tolist()
labels = [str(i) for i in lengths_list]
peak_lengths = pd.DataFrame.from_dict({'coords': labels,
'lengths': lengths_list},
orient='columns')
What works:
alt.Chart(peak_lengths).mark_bar().encode(
x = alt.X('lengths:Q', bin=True),
y='count(*):Q'
)
What doesn't work:
plotAltair = True
if plotAltair:
alt.Chart(peak_lengths).mark_bar().encode(
x = alt.X('lengths:Q', bin=True),
y='count(*):Q'
)
** Obs.: I have already attempted to use alt.data_transformers.enable('json')
as a way of reducing file size and it is also not working, but let's please not focus on this but rather on the more simple question.
Upvotes: 3
Views: 2136
Reputation: 86433
Short answer: use chart.display()
Long answer: Jupyter notebooks in general will only display things if you tell them to. For example, this code will not result in any output:
if x:
x + 1
You are telling the notebook to evaluate x + 1
, but not to do anything with it. What you need to do is tell the notebook to print the result, either implicitly by putting it as the last line in the main block of the cell, or explicitly by asking for it to be printed when the statement appears anywhere else:
if x:
print(x + 1)
It is similar for Altair charts, which are just normal Python objects. If you put the chart at the end of the cell, you are implicitly asking for the result to be displayed, and Jupyter will display it as it will any variable. If you want it to be displayed from any other location in the cell, you need to explicitly ask that it be displayed using the IPython.display.display()
function:
from IPython.display import display
if plotChart:
chart = alt.Chart(data).mark_point().encode(x='x', y='y')
display(chart)
Because this extra import is a bit verbose, Altair provides a .display()
method as a convenience function to do the same thing:
if plotChart:
chart = alt.Chart(data).mark_point().encode(x='x', y='y')
chart.display()
Note that calling .display()
on multiple charts is the way that you can display multiple charts in a single cell.
Upvotes: 7