bwarren2
bwarren2

Reputation: 1387

Altair color scale range misaligned

I am trying to set custom color breakpoints on a choropleth, but the scale doesn't appear to be honoring my skewed color placement. For example:

counties = alt.topo_feature(vega_data.us_10m.url, 'counties')

states = alt.topo_feature(vega_data.us_10m.url, 'states')

outlines = alt.Chart(states).mark_geoshape(
    stroke='black'
).project('albersUsa')

domain = [df.min()['rep_vote_change'], 0, df.max()['rep_vote_change']]
range_ = ['darkred', 'orange', 'green']
colors = alt.Chart(counties).mark_geoshape().encode(
    color=alt.Color('rep_vote_change:Q', scale=alt.Scale(domain=domain, range=range_))
).transform_lookup(
    lookup='id',
    from_=alt.LookupData(df, 'id', ['rep_vote_change'])
).project(
    type='albersUsa'
).properties(
    width=500,
    height=300
)

colors + outlines 

produces:

enter image description here

Note how the orange is not centered at 0. How do I force the scale color to match my domain breakpoints?

Upvotes: 0

Views: 3192

Answers (1)

jakevdp
jakevdp

Reputation: 86328

You'll need to set the scale type to "linear" for it to work the way you expect. For example (using a simpler chart because you didn't provide your data):

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

df = pd.DataFrame({
    'x': np.random.randn(100),
    'y': np.random.randn(100),
    'c': np.random.choice([-10, 0, 1], 100)
})

scale = alt.Scale(
    domain=[-10, 0, 1],
    range=['darkred', 'orange', 'green'],
    type='linear'
)

alt.Chart(df).mark_point().encode(
  x='x',
  y='y',
  color=alt.Color('c', scale=scale)
)

enter image description here

The linear scale type will be the default for piecewise color scales in a future release; more details at https://github.com/vega/vega-lite/issues/3980

Upvotes: 6

Related Questions