Altair色标范围未对齐

时间:2019-03-19 16:07:11

标签: python vega altair

我正在尝试在Choropleth上设置自定义颜色断点,但是该比例似乎不符合我偏斜的颜色位置。例如:

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 

产生:

enter image description here

请注意橙色如何不居中于0。如何强制比例颜色与域断点匹配?

1 个答案:

答案 0 :(得分:2)

您需要将比例类型设置为"linear",以使其按预期方式工作。例如(使用更简单的图表,因为您没有提供数据):

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

在将来的发行版中,线性色标类型将是分段色标的默认设置;有关更多详细信息,请访问https://github.com/vega/vega-lite/issues/3980