簡體   English   中英

Altair為條形圖設置常量標簽顏色

[英]Altair setting constant label color for bar chart

在以下官方網站中提供了在Altair中設置條形圖標簽的示例: https : //altair-viz.github.io/gallery/bar_chart_with_labels.html

但是,一旦您想在條形圖中將“ color”參數設置為一個變量,標簽顏色就會自動匹配條形的顏色,如下所示。 但是,我的目的是使標簽顏色始終保持不變,就像一直保持黑色。 如果要將標簽顯示為百分比,則這對於堆疊條形圖尤其理想。 在mark_text中設置“ color ='black'”似乎不起作用。 可能是因為它基於使用“顏色”參數作為“年份”的“條”。 但是我找不到解耦此參數的直觀方法。

import altair as alt
from vega_datasets import data

source = data.wheat()

bars = alt.Chart(source).mark_bar().encode(
    x='wheat:Q',
    y="year:O",
    color='year:O'

)

text = bars.mark_text(
    align='left',
    baseline='middle',
        color='black',
    dx=3  # Nudges text to right so it doesn't appear on top of the bar
).encode(
    text='wheat:Q'

)

(bars + text).properties(height=900)

帶有可變標簽顏色的條形圖

帶彩色標簽的堆疊條形圖示例

當您執行bars.mark_text() ,結果圖表將繼承您在條形圖中指定的所有內容,包括顏色編碼。 為了避免對文本進行顏色編碼,最好的方法是確保其不繼承顏色編碼。

例如:

import altair as alt
from vega_datasets import data

source = data.wheat()

base = alt.Chart(source).encode(
    x='wheat:Q',
    y="year:O"
)

bars = base.mark_bar().encode(
    color='year:O'
)

text = base.mark_text(
    align='left',
    baseline='middle',
    dx=3  # Nudges text to right so it doesn't appear on top of the bar
).encode(
    text='wheat:Q'
)

(bars + text).properties(height=900)

mark_text(color='black')不會覆蓋代碼段中的編碼的原因是,如Global Config vs. Local Config vs. Encoding中所述,顏色編碼優先於標記屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM