使用Altair生成水平条形图并水平连接表格

3
如果可能的话,我想使用Altair创建一个水平条形图,其中包含来自水平连接的表中的一列或多列,并与条形对齐。我粘贴了一个快速Excel图表的示例,以便大致了解我的要求。

example

下面是来自您网站的示例(先是代码,然后是图片),我为了节省空间进行了子集处理,类似于我想要的。但是,与其有一个文本叠加层,该层包含与棒长度相对应的值,我想要创建一个水平条形图,其中包含值“x”,以及一个水平连接的表格,其中包含一个单独的值“p”,该值对应于该样本。
import altair as alt
from vega_datasets import data

source = data.wheat()
sourceTrunc = source.head(15)

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

text = bars.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=400)

foundation

1个回答

2
您可以使用水平连接来代替分层以实现这一点。例如:
import altair as alt
from vega_datasets import data

source = data.wheat()
sourceTrunc = source.head(15)

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

text = alt.Chart(sourceTrunc).mark_text().encode(
    y=alt.Y('year:O', axis=None),
    text='wheat:Q'
).properties(width=30)

bars | text

enter image description here


谢谢。这个可行。但我有一个后续问题。由于它被编码为纵轴,添加标题会将其放在纵轴的左侧(这也是您可能声明为“无”的原因)。是否有一种方法可以将标题放在顶部或底部,以使其看起来像列? - Protaeus
1
这听起来像是你在设置坐标轴标题。如果你想要一个图表标题,请使用.properties(title='the title') - jakevdp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接