looking for help on how to load an altair chart from a json file (contains dict_keys(['$schema', 'config', 'datasets', 'title', 'vconcat'])
).
The json file was created using the altair.Chart
method to_json()
such as below:
import altair as alt
chart = alt.Chart(df).mark_line(...).encode(...).properties(...).transform_filter(...)
chart_json = chart.to_json()
Here is a sample of the code I would like to run
chart = alt.load_json(chart_json) # made-up, needs replacement
chart.save('chart.png')
Disclaimer: I've never used altair and am trying to reverse-engineer a project. Thanks in advance for the help!
CodePudding user response:
Altair can work directly with json files by specifying their path/url as shown in the documentation:
import altair as alt
from vega_datasets import data
url = data.cars.url # URL/path to json data
alt.Chart(url).mark_point().encode(
x='Horsepower:Q',
y='Miles_per_Gallon:Q'
)
To load a local file, there are several potential issues, including the browser having access to local files and using the correct format for the frontend you're using (e.g. jupyterlab). These have been elaborated on elsewhere:
- Reference local .csv file in altair chart
- https://github.com/altair-viz/altair/issues/2529#issuecomment-982643293
- https://github.com/altair-viz/altair/issues/2432
CodePudding user response:
It sounds like you're looking for the alt.Chart.from_json
method:
new_chart = alt.Chart.from_json(chart_json)
new_chart.display()
The method assumes that chart_json
is a string of JSON representing a valid Altair chart.