Displaying specified color in layered Altair charts

Question:

I am trying to make a layered chart in Altair and running into an issue.
Sample code

df  = pd.DataFrame(np.array([["A", 2021, 0.9, 0.5], 
                             ["A", 2020, 0.8, 0.7],
                             ["B", 2021, 0.6, 0.5], 
                             ["B", 2020,  0.8, 0.7]]),
                   columns=['Category', 'Year', 'Count_%_All', 'Count_%_Industry'])

domain =['A', 'B']
range_ = ['red', 'red']

chart_1 = alt.Chart(df).mark_line(point = True).encode(
    x=alt.X('Year:O', title=None  ),
    y=alt.Y('Count_%_All:Q', title = "% Companies", axis=alt.Axis(format='%',grid = False)   ),
    color = alt.Color('Category:N', scale=alt.Scale(domain=domain, range=range_)),
    
)


domain_1 =['A', 'B']
range_1 = ['green', 'blue']

chart = alt.Chart(df).mark_bar().encode(
    x=alt.X('Year:O', title=None  ),
    y=alt.Y('Count_%_Industry:Q', title = "% Companies", axis=alt.Axis(format='%',grid = False)   ),
    color = alt.Color('Category:N',scale=alt.Scale(domain=domain_1, range=range_1), legend = None),
    
)

final  = alt.layer(chart, chart_1, data=df).facet(column='Category:N') 
final

This gives the following result

  • enter image description here

The issue that I am facing is –

  1. For the line chart, I am specifying red color where as in the final chart I am getting the colors same as the bars – how do I solve this?

Thanks

Asked By: Green Finance

||

Answers:

You have to resolve the color scale. See also https://altair-viz.github.io/user_guide/scale_resolve.html?highlight=resolve_scale.

alt.layer(chart, chart_1).resolve_scale(color='independent').facet(column='Category:N')

results in:
enter image description here

Answered By: debbes

Add resolve_scale(color='independent') to your layer, before faceting:

final  = alt.layer(chart, chart_1, data=df).resolve_scale(color='independent').facet(column='Category:N')
final

enter image description here

Answered By: Mattijn
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.