🌟
StreamlitでVega-Liteを描画する
問題
Pythonのデータ可視化ライブラリAltair-Vegaは,Vega-Lite用JSONビルダー的なもので,Pythonを使ってVega-Liteの仕様に沿ったJSONを組み立てることができます.
Vega-Lite JSONとAltair Chartは,お互いに変換することができます.
chart = alt.Chart.from_json(vega_spec)
vega_spec = chart.to_json()
そこで以下のようにVega-Lite JSONをAltair Chartに変換し,Streamlitで描画しようとしましたが,なぜか描画されませんでした.ここで使っているVega-Lite JSONはVega Editorで動作することを確認済みです.
import streamlit as st
import altair as alt
import json
vega_spec = """{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"description": "A simple bar chart with embedded data.",
"data": {
"values": [
{"a": "A", "b": 28}, {"a": "B", "b": 55}, {"a": "C", "b": 43},
{"a": "D", "b": 91}, {"a": "E", "b": 81}, {"a": "F", "b": 53},
{"a": "G", "b": 19}, {"a": "H", "b": 87}, {"a": "I", "b": 52}
]
},
"mark": "bar",
"encoding": {
"x": {"field": "a", "type": "nominal", "axis": {"labelAngle": 0}},
"y": {"field": "b", "type": "quantitative"}
}
}
"""
chart = alt.Chart.from_json(vega_spec)
st.altair_chart(chart, use_container_width=True)
解決
このIssueにあるように,st.altair_chart
ではなくst.vega_lite_chart
を使って直接Vega-Liteを描画したほうがいいみたいです.
import streamlit as st
import altair as alt
import json
vega_spec = """{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"description": "A simple bar chart with embedded data.",
"data": {
"values": [
{"a": "A", "b": 28}, {"a": "B", "b": 55}, {"a": "C", "b": 43},
{"a": "D", "b": 91}, {"a": "E", "b": 81}, {"a": "F", "b": 53},
{"a": "G", "b": 19}, {"a": "H", "b": 87}, {"a": "I", "b": 52}
]
},
"mark": "bar",
"encoding": {
"x": {"field": "a", "type": "nominal", "axis": {"labelAngle": 0}},
"y": {"field": "b", "type": "quantitative"}
}
}
"""
- chart = alt.Chart.from_json(vega_spec)
- st.altair_chart(chart, use_container_width=True)
+ st.vega_lite_chart(json.loads(vega_spec), use_container_width=True)
Altairを使うことばかり考えてたので沼った.
Discussion