Altair高度条件中的动态名称 [英] dynamic name in Altair alt.condition
问题描述
我将按照以下示例创建一个条形图,其条件色格式为负值:
import altair as alt $来自vega_datasets的b $ b导入数据
source = data.us_employment()
alt.Chart(source).mark_bar()。encode(
x = month :T,
y = nonfarm_change:Q,
color = alt.condition(
alt.datum.nonfarm_change> 0,
alt.value( steelblue) ,#正色
alt.value(橙色)#负色
)
).properties(width = 600)
如何用接受动态变量名称的表达式替换 alt.datum.nonfarm_change
数据框的不同列?
Python提供了 getattr
函数使您可以从任何Python对象获取动态属性,因此可以使用 getattr(alt.datum,col_name)
从获取动态列名。 alt.datum
对象。
但是直接将过滤条件指定为字符串可能更容易;像这样的东西(它使用了
I am following this example to create a bar chart with conditional color formatting on negative values:
import altair as alt
from vega_datasets import data
source = data.us_employment()
alt.Chart(source).mark_bar().encode(
x="month:T",
y="nonfarm_change:Q",
color=alt.condition(
alt.datum.nonfarm_change > 0,
alt.value("steelblue"), # The positive color
alt.value("orange") # The negative color
)
).properties(width=600)
How can I replace alt.datum.nonfarm_change
with an expression accepting a dynamic variable name e.g. different columns of a dataframe?
Python provides a getattr
function that lets you get a dynamic attribute from any Python object, so you could use getattr(alt.datum, col_name)
to get a dynamic column name from the alt.datum
object.
But it's probably easier to specify your filter condition as a string directly; something like this (which makes use of f-strings):
import altair as alt
from vega_datasets import data
def plot_column(col_name: str) -> alt.Chart:
source = data.us_employment()
return alt.Chart(source).mark_bar().encode(
x="month:T",
y=f"{col_name}:Q",
color=alt.condition(
f"datum.{col_name} > 0",
alt.value("steelblue"), # The positive color
alt.value("orange") # The negative color
)
).properties(width=600)
plot_column("nonfarm_change")
这篇关于Altair高度条件中的动态名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!