【问题标题】:Altair Bar Chart - label placement and formatingAltair 条形图 - 标签放置和格式设置
【发布时间】:2020-08-22 17:54:47
【问题描述】:

跟进this question 我还有两个额外的选项可以实现:

  1. 将标签的位置设置为图表中间,无论条形高度如何
  2. 格式标签显示为字符串的一部分,包括括号

我的代码目前如下所示:

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)

关于位置,我尝试了使用docs here 的MarkDef 的不同参数,但没有找到允许相对于图表而不是条形的位置的选项。 如上图foo bar 所示,我想避免标签出现在 Y 轴区域之外的情况。

关于格式,我尝试实施解决方案here,但由于某种原因在我的情况下不起作用。 理想情况下,我希望格式为 label='"(" + datum.coloring_value + ")"'),但使用括号会导致 JavaScript 错误:

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

这可以吗? 谢谢!

【问题讨论】:

    标签: python altair streamlit


    【解决方案1】:

    您的文本的 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)
    

    【讨论】:

      猜你喜欢
      • 2020-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-04
      • 1970-01-01
      相关资源
      最近更新 更多