我正在尝试创建一个 Altair 多面条形图,其中的线条代表其他度量,最好使用右侧的第二个 y 轴。我不知道是否可以使用Atair。代码如下:
import altair as alt
import pandas as pd
data = {
'Date': ['2023-01-01', '2023-01-02', '2023-01-01', '2023-01-02', '2023-01-01', '2023-01-02', '2023-01-01', '2023-01-02', '2023-01-01', '2023-01-02', '2023-01-01', '2023-01-02', '2023-01-01', '2023-01-02', '2023-01-01', '2023-01-02'],
'Value': [50, 200, 300, 150, 250, 350, 200, 200, 10, 20, 15, 20, 20, 30, 20, 30],
'DESCR': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'D', 'D', 'D', 'D'],
'Company': ['X', 'X', 'Y', 'Y', 'X', 'X', 'Y', 'Y', 'X', 'X', 'Y', 'Y', 'X', 'X', 'Y', 'Y'],
}
source = pd.DataFrame(data)
bars = alt.Chart(source).mark_bar().transform_filter(f"(datum.DESCR=='A') | (datum.DESCR=='B')").encode(
x='Date:N',
y='Value:Q',
color=alt.Color('DESCR:N', legend=alt.Legend(title=None))
)
lines = alt.Chart(source).mark_line().transform_filter(f"(datum.DESCR=='C') | (datum.DESCR=='D')").encode(
x='Date:N',
y='Value',
stroke=alt.Stroke('DESCR', legend=alt.Legend(title=None), scale=alt.Scale(scheme='redblue'))
)
chart = (bars+lines).facet(column='Company')
chart
我在.facet之后尝试过.resolve_scale(y='independent'),但它没有显示右侧的第二个轴。
如有任何帮助,我们将不胜感激。
根据https://github.com/vega/vega-lite/issues/4373#issuecomment-617153232,您需要一些额外的解决方案:
chart = (
(bars+lines)
.resolve_scale(y='independent') # Create dual axis
.facet(column='Company')
.resolve_axis(y='independent') # Make sure dual axis works with facet (redraws the axis for each subplot)
.resolve_scale(y='shared') # Set the y-max across facets to be the same (the default when not having dual axes)
)