[英]Add legend to line & bars to Altair chart without using size/color
[英]Can you add a label for “missing data” to a legend for an Altair chart?
我有一個使用 Altair 繪制的熱圖,其中包含一個顏色條,但熱圖中缺失的數據(空白/白色)未在顏色條上標記。 有沒有辦法將單獨的 label 添加到圖例(例如顏色條下方)以顯示圖表中缺失數據的表示方式?
我想出了一個解決方案,它在我的圖表頂部包含一個“幽靈”層——一個大小為 0 的標尺圖表(因此該線是不可見的),它由一個填充有字符串值“否”的列着色數據”(見下面的代碼)。 這會強制使用傳奇項目,但我想知道是否有更好的方法。 (請參閱此處鏈接中的完整示例:熱圖 plot )
import numpy as np
import altair as alt
import pandas as pd
# Example heatmap data
heatmap_df = pd.DataFrame([["NY",1999,1],["NY",2000,np.nan], ["MA",1999,np.nan], ["MA",2000,4]], columns = ["state","year","rate"])
# Example Legend dataframe
legend_no_data = pd.DataFrame([[1999, "No Data"]], columns = ["year", "text"])
# Example chart with "No Data" label
heatmap = alt.Chart(heatmap_df).mark_rect().encode(alt.X("year:O"), alt.Y("state:N"), alt.Color("rate:Q"))
# Chart for "No Data" legend item
vacc_legend_no_data = alt.Chart(legend_no_data).mark_line(
size=0
).encode(
x='year:O',
color = alt.Color("text:N", legend = alt.Legend(title = "", symbolType = "square")))
heatmap + vacc_legend_no_data
“ghost layer”在顏色條底部添加了標有“No Data”的空方塊,但我希望有更好的方法來表示這個!
不幸的是,我不知道在定量范圍內處理空值的簡單方法。 但是您可以在名義范圍內自然地處理它們; 我可能會使用計算轉換在圖表規范中生成 Null 數據集層,以避免構建第二個 dataframe。 它可能看起來像這樣:
heatmap = alt.Chart(heatmap_df).mark_rect().encode(
alt.X("year:O"),
alt.Y("state:N"),
alt.Color("rate:Q")
)
nulls = heatmap.transform_filter(
"!isValid(datum.rate)"
).mark_rect(opacity=0.5).encode(
alt.Color('rate:N', scale=alt.Scale(scheme='greys'))
)
heatmap + nulls
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.