简体   繁体   English

是否可以在 Altair 中对具有多个数据源的分层图表进行分面?

[英]Is it possible to facet a layered chart with multiple data sources in Altair?

My question is similar to the one here , however I cannot figure out how to specify the data correctly.我的问题与此处的问题类似,但是我无法弄清楚如何正确指定数据。

I am trying to create a layered bar and tick chart with faceting.我正在尝试创建一个带有分面的分层条形图和刻度图。 You cannot layer a faceted chart, so I have to specify the data and faceting in the parent layered chart.您不能对分面图表进行分层,因此我必须在父分层图表中指定数据和分面。 Following the example in the question linked, I have added a second data set for layering while also keeping the facet:按照链接问题中的示例,我添加了第二个数据集用于分层,同时还保留了方面:

bars = pd.DataFrame({
    'year': np.repeat([2018, 2019], 6),
    'cat1': np.tile(['a', 'a', 'a', 'b', 'b', 'b'], 2),
    'cat2': np.tile(list('XYZ'), 4),
    'vals': np.arange(1, 13)
})

ticks = pd.DataFrame({
    'year': np.repeat([2018, 2019], 2),
    'cat1': np.tile(['a', 'b'], 2),
    'limit': [8, 13, 25, 32]
})

b = alt.Chart().mark_bar().encode(
    x='year:O',
    y='vals',
    color='cat2',
).properties(width=100)

t = alt.Chart(ticks).mark_tick(color='black', thickness=2, width=40).encode(
    x='year:O',
    y='limit',
)

alt.layer(b, t, data=bars).facet(
    'cat1:N',
)

刻度过多的图表

My problem is that I would like the tick marks to be facetted as well.我的问题是我希望刻度线也有刻面。 Is this possible without combining the datasets?如果不组合数据集,这可能吗?

For example, this solution works by merging the data together first, but it is also drawing multiple ticks on top of each other:例如,此解决方案首先将数据合并在一起,但它也会在彼此之上绘制多个刻度:

bars_and_ticks = bars.merge(ticks, on=['year', 'cat1'])

t = alt.Chart().mark_tick(color='black', thickness=2, width=40).encode(
    x='year:O',
    y='limit',
)

alt.layer(b, t, data=bars_and_ticks).facet(
    'cat1:N',
)

You can only facet by a single dataset.您只能通过单个数据集进行分面。 I would approach what you want to do by combining your inputs into a single dataframe, and building the chart from there.我会通过将您的输入组合到一个数据框中并从那里构建图表来接近您想要做的事情。 For example:例如:

import pandas as pd
import numpy as np
import altair as alt

bars = pd.DataFrame({
    'year': np.repeat([2018, 2019], 6),
    'cat1': np.tile(['a', 'a', 'a', 'b', 'b', 'b'], 2),
    'cat2': np.tile(list('XYZ'), 4),
    'vals': np.arange(1, 13)
})

ticks = pd.DataFrame({
    'year': np.repeat([2018, 2019], 2),
    'cat1': np.tile(['a', 'b'], 2),
    'limit': [8, 13, 25, 32]
})

data = pd.merge(bars, ticks, how='left', on=['year', 'cat1'])

b = alt.Chart(data).mark_bar().encode(
    x='year:O',
    y='vals',
    color='cat2',
).properties(width=100)

t = alt.Chart(data).mark_tick(color='black', thickness=2, width=40).encode(
    x='year:O',
    y='max(limit):Q',
)

alt.layer(b, t).facet(
    'cat1:N',
)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM