Altair 分层图表(条形图和线条)无法更改线条的颜色

问题描述 投票:0回答:1

我正在使用 Altair 创建带有条形图和折线图的分层图表。在这个简单的例子中,我试图用不同的颜色制作笔画,但没有成功。我尝试过对描边使用比例方案,但它没有改变颜色。

有人可以帮忙吗?

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, 200, 200, 200, 200, 300, 300, 300, 300],
    '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)
source_aux = source[(source['DESCR']=='C') | (source['DESCR']=='D')]
source = source[(source['DESCR']=='A') | (source['DESCR']=='B')]

bars = alt.Chart().mark_bar().encode(
    x='Date:N',
    y='Value:Q',
    color=alt.Color('DESCR:N', legend=alt.Legend(title=None))
)

limits = alt.Chart(source_aux).mark_rule().encode(
    y='Value',
    strokeDash=alt.StrokeDash('DESCR', legend=alt.Legend(title=None))
)

chart = alt.layer(
    bars,
    limits,
    data=source
).facet(
    column='Company:N'
)

chart
python charts altair
1个回答
0
投票

strokeDash
控制线条的虚线,但对颜色没有影响。要更改线条的颜色,您可以使用
stroke
color
编码。

enter image description here

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, 200, 200, 200, 200, 300, 300, 300, 300],
    '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)
source_aux = source[(source['DESCR']=='C') | (source['DESCR']=='D')]
source = source[(source['DESCR']=='A') | (source['DESCR']=='B')]

bars = alt.Chart().mark_bar().encode(
    x='Date:N',
    y='Value:Q',
    color=alt.Color('DESCR:N', legend=alt.Legend(title=None))
)

limits = alt.Chart(source_aux).mark_rule().encode(
    y='Value',
    strokeDash=alt.StrokeDash('DESCR', legend=alt.Legend(title=None)),
    stroke=alt.Stroke('DESCR', legend=alt.Legend(title=None))
)

chart = alt.layer(
    bars,
    limits,
    data=source
).facet(
    column='Company:N'
)

chart
© www.soinside.com 2019 - 2024. All rights reserved.