![](/img/trans.png)
[英]Bold some of the x-labels with alt.condition in Altair plot
[英]dynamic name in Altair alt.condition
我正在按照此示例創建一個條形圖,該條形圖帶有負值的條件顏色格式:
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)
如何用接受動態變量名稱的表達式替換alt.datum.nonfarm_change
,例如數據幀的不同列?
Python 提供了一個getattr
函數,可讓您從任何 Python 對象獲取動態屬性,因此您可以使用getattr(alt.datum, col_name)
從alt.datum
對象獲取動態列名。
但直接將過濾條件指定為字符串可能更容易; 像這樣(使用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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.