如何在 Altair 中将配色方案设置为主题
How can I set a color scheme as a theme in 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,我尝试了几次,但都没有成功。
您需要配置 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'
)
在每个 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,我尝试了几次,但都没有成功。
您需要配置 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'
)