跟进this question我还有两个额外的选项需要实现:
- 将标签放置在图表中间,无论条形高度如何
- 格式化标签以显示为包含括号的字符串的一部分
我的代码目前如下所示:
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 栏所示,我希望避免标 checkout 现在 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.
这可以做到吗? 谢谢!
最佳答案
您的文本的 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)
关于python - Altair 条形图 - 标签放置和格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61657741/