[英]Bullet chart in Altair
我試圖在Altair中重現這張Vega-lite圖表 ,但遇到一些問題。 這是我到目前為止的內容:
# data import and prep
import json
import altair as alt
import pandas as pd
df = pd.read_json("""[{"title":"Revenue","subtitle":"US$, in thousands","ranges":[150,225,300],"measures":[220,270],"markers":250},
{"title":"Profit","subtitle":"%","ranges":[20,25,30],"measures":[21,23],"markers":26},
{"title":"Order Size","subtitle":"US$, average","ranges":[350,500,600],"measures":[100,320],"markers":550},
{"title":"New Customers","subtitle":"count","ranges":[1400,2000,2500],"measures":[1000,1650],"markers":2100},
{"title":"Satisfaction","subtitle":"out of 5","ranges":[3.5,4.25,5],"measures":[3.2,4.7],"markers":4.4}]""")
df[['measure1','measure2']] = pd.DataFrame(df.measures.values.tolist(), index=df.index)
df[['low', 'medium', 'high']] = pd.DataFrame(df.ranges.values.tolist())
# chart
base = alt.Chart(df).encode(row = 'title:O')
m1 = base.mark_bar().encode(x='measure1:Q')
m2 = base.mark_tick().encode(x='measure2:Q')
到現在為止還挺好。 但是,當我嘗試對兩個圖表進行分層時:
m1 + m2
SchemaValidationError: Invalid specification
altair.vegalite.v2.api.LayerChart->layer->items, validating 'anyOf'
{'data': {'name': 'data-58353a9bcf31ee710e2a5cb2da21a143'}, 'mark': 'bar', 'encoding': {'row': {'type': 'nominal', 'field': 'title'}, 'x': {'type': 'quantitative', 'field': 'measure1'}}} is not valid under any of the given schemas
請注意,如果我在兩個圖層和最后一個方面都指定了y
編碼,則此方法有效,但是這違背了具有多個切面的目的(所有Y軸標記都在所有切面中重復。如果我在基圖中未指定row
編碼也不使用y
編碼,只會繪制一個條形圖(最大的一個)。
我需要構面的原因是,鑒於數據的不同域,我可以指定獨立的x比例(請參見原始示例)。
謝謝你的幫助!
在Altair和vega-lite中,對兩個多面圖表進行分層都是無效的(通常,不能保證在分層時兩個多面圖表會對齊)。 如果您仔細觀察素食主義者圖表,您會發現它不是分層的多面圖,而是分層的圖。
在Altair中可以通過以下方式完成相同的操作:
import altair as alt
import pandas as pd
df = pd.DataFrame.from_records([
{"title":"Revenue","subtitle":"US$, in thousands","ranges":[150,225,300],"measures":[220,270],"markers":[250]},
{"title":"Profit","subtitle":"%","ranges":[20,25,30],"measures":[21,23],"markers":[26]},
{"title":"Order Size","subtitle":"US$, average","ranges":[350,500,600],"measures":[100,320],"markers":[550]},
{"title":"New Customers","subtitle":"count","ranges":[1400,2000,2500],"measures":[1000,1650],"markers":[2100]},
{"title":"Satisfaction","subtitle":"out of 5","ranges":[3.5,4.25,5],"measures":[3.2,4.7],"markers":[4.4]}
])
alt.layer(
alt.Chart().mark_bar(color='#eee').encode(alt.X("ranges[2]:Q", scale=alt.Scale(nice=False), title=None)),
alt.Chart().mark_bar(color='#ddd').encode(x="ranges[1]:Q"),
alt.Chart().mark_bar(color='#ccc').encode(x="ranges[0]:Q"),
alt.Chart().mark_bar(color='lightsteelblue', size=10).encode(x='measures[1]:Q'),
alt.Chart().mark_bar(color='steelblue', size=10).encode(x='measures[0]:Q'),
alt.Chart().mark_tick(color='black').encode(x='markers[0]:Q'),
data=df
).facet(
row="title:O"
).resolve_scale(
x='independent'
)
原始圖表中的某些樣式/配置選項丟失了,但這是一個粗略的主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.