簡體   English   中英

Altair 條形圖 - label 放置和格式化

[英]Altair Bar Chart - label placement and formating

跟進這個問題,我還有兩個額外的選項可以實現:

  1. 將 label 的位置設置在圖表中間,無論條形高度如何
  2. 將 label 格式化為字符串的一部分,包括括號

我的代碼目前如下所示:

df = pd.DataFrame({'name':['bar','foo'],
                  'presented_value':[2,20],
                  'coloring_value':[1,25]})

base = (alt.Chart(df, height=250, width=375).mark_bar()
 .encode(
    x='name',
    y=alt.Y('presented_value', axis=alt.Axis(orient='right')),
    color='name'
  )
)
bars = base.mark_bar().encode(color=alt.condition(
      alt.datum.presented_value > alt.datum.coloring_value,
      alt.value('lightgreen'),
      alt.value('darkred')
    ))

text_sub_brand = base.mark_text(
    align='center', baseline='bottom', 
    dy=35, fontSize=24
).encode(
    text='presented_value'
)
text_cluster = base.mark_text(
    align='center', baseline='bottom', 
    dy=50, fontSize=16
).encode(
    text='coloring_value'
).transform_calculate(label='"Cluster value: " + datum.coloring_value')


(bars + text_sub_brand + text_cluster).properties(width=700)

在此處輸入圖像描述

關於放置,我使用此處的文檔嘗試了MarkDef的不同參數,但沒有找到允許相對於圖表而不是條形放置的選項。 如上圖foo bar 所示,我想避免 label 出現在 Y 軸區域之外的情況。

關於格式,我嘗試在此處實施解決方案,但由於某種原因在我的情況下不起作用。 理想情況下,我希望格式為label='"(" + datum.coloring_value + ")"')但使用括號會導致 JavaScript 錯誤:

This usually means there's a typo in your chart specification. See the javascript console for the full traceback.

這可以做到嗎? 謝謝!

您的文本已將 y 編碼設置為presented_value ,因此它將根據此出現在圖表上。 如果您希望它位於圖表上的固定位置,您可以將 y 編碼設置為alt.value(pixels_from_top)

對於格式,您可以使用計算轉換,然后在文本編碼中引用此計算值。

放在一起,它看起來像這樣:

import altair as alt
import pandas as pd

df = pd.DataFrame({'name':['bar','foo'],
                  'presented_value':[2,20],
                  'coloring_value':[1,25]})

base = (alt.Chart(df, height=250, width=375).mark_bar()
 .encode(
    x='name',
    y=alt.Y('presented_value', axis=alt.Axis(orient='right')),
    color='name'
  )
)
bars = base.mark_bar().encode(color=alt.condition(
      alt.datum.presented_value > alt.datum.coloring_value,
      alt.value('lightgreen'),
      alt.value('darkred')
    ))

text_sub_brand = base.mark_text(
    align='center', baseline='bottom', 
    dy=35, fontSize=24
).encode(
    y=alt.value(100),
    text='presented_value'
)
text_cluster = base.mark_text(
    align='center', baseline='bottom', 
    dy=50, fontSize=16
).encode(
    y=alt.value(100),
    text='label:N'
).transform_calculate(label='"(" + datum.coloring_value + ")"')


(bars + text_sub_brand + text_cluster).properties(width=700)

在此處輸入圖像描述

暫無
暫無

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

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