ffi*_*ffi 3 python-3.x jupyter altair
情况似乎很简单:我正在处理带有多个 Altair 图的 Jupyter Lab 文件,这最终使文件太大而无法运行和保存。由于我不需要每次都看到这些图,我想我可以通过plotAltair = True在脚本开头指定类似的内容然后将每个 Altair 图嵌套在if语句中来避免这种情况。这听起来很简单,但由于某种原因,它似乎不起作用。我错过了一些明显的东西吗?[编辑:原来我是]
例如:
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')
Run Code Online (Sandbox Code Playgroud)
什么工作:
alt.Chart(peak_lengths).mark_bar().encode(
x = alt.X('lengths:Q', bin=True),
y='count(*):Q'
)
Run Code Online (Sandbox Code Playgroud)
什么不起作用:
plotAltair = True
if plotAltair:
alt.Chart(peak_lengths).mark_bar().encode(
x = alt.X('lengths:Q', bin=True),
y='count(*):Q'
)
Run Code Online (Sandbox Code Playgroud)
** Obs.:我已经尝试将其alt.data_transformers.enable('json')用作减小文件大小的方法,但它也不起作用,但请不要关注此问题,而是关注更简单的问题。
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
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
Note that calling .display() on multiple charts is the way that you can display multiple charts in a single cell.
| 归档时间: |
|
| 查看次数: |
1309 次 |
| 最近记录: |