我正在尝试在Altair中复制this Vega-lite chart,但是遇到一些问题。这是我到目前为止的内容:
# 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比例(请参见原始示例)。
感谢您的帮助!
答案 0 :(得分:2)
在Altair和vega-lite中,对两个多面图表进行分层都是无效的(通常,不能保证在分层时两个多面图表会对齐)。如果您仔细观察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'
)
原始图表中缺少一些样式/配置选项,但这是一个粗略的主意。