python - 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
产生:
请注意橙色不是以 0 为中心的。如何强制比例颜色与我的域断点匹配?
解决方案
您需要将比例类型设置为"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)
)
线性比例类型将是未来版本中分段颜色比例的默认值;更多详细信息,请访问https://github.com/vega/vega-lite/issues/3980
推荐阅读
- ruby - 错误:没有这样的过滤器:“电影”,有什么问题?
- pandas - 过滤具有多个(> 100)列条件的熊猫行
- python - 具有无组织 json 输出的 Python API
- python-3.x - 使用卡恩算法返回图中的所有拓扑排序顺序?
- javascript - react-bootstrap-tabs 库,编译错误
- python - Python切片数组获取除一些索引之外的所有内容
- javascript - 尝试在 discord.js 中记录消息
- javascript - 为 javascript 创建代码以包含“客户”对象
- r - 多次运行函数并将值存储在 R 中的向量中
- ajax - 模态不会以编程方式显示