如何在Altair中将配色方案设置为主题

时间:2020-07-04 15:18:36

标签: python altair

在每个Altair图中使用color scheme(例如set2)很容易:

import pandas as pd 
import altair as alt
from sklearn.datasets import load_iris

data_iris = load_iris()
df = pd.DataFrame(data_iris["data"], columns=data_iris["feature_names"])
df["species"] = [data_iris["target_names"][i] for i in data_iris["target"]]

alt.Chart(df).mark_circle().encode(
    x=alt.X("sepal width (cm)", scale=alt.Scale(zero=False)), 
    y=alt.Y("sepal length (cm)", scale=alt.Scale(zero=False)),
    color=alt.Color("species", 
                    scale=alt.Scale(scheme="set2") ## should be in theme
                   )
)

我想在所有图表中使用颜色主题,但是我找不到将颜色方案配置为Altair方案的方法。

import altair as alt

def my_theme():
    return {"config": None} ## How can we set the color scheme here?

alt.themes.register('my_theme', my_theme)
alt.themes.enable('my_theme')

通过阅读Documentation,我尝试了几次,但没有成功。

1 个答案:

答案 0 :(得分:2)

您将需要配置range参数。有关更多详细信息,请参见Scale Range Properties

import altair as alt
from vega_datasets import data

# define the theme by returning the dictionary of configurations
def my_theme():
    return {
        'config': {
            'view': {
                'height': 300,
                'width': 400,
            },
            'range': {
                'category': {'scheme':'set2'}
            }
        }
    }

# register the custom theme under a chosen name
alt.themes.register('my_theme', my_theme)

# enable the newly registered theme
alt.themes.enable('my_theme')

# draw the chart
cars = data.cars.url
alt.Chart(cars).mark_point().encode(
    x='Horsepower:Q',
    y='Miles_per_Gallon:Q', 
    color='Origin:N'
)

enter image description here