如何在 altair 中绘制一条跨越垂直连接图的线?

How to draw a line that spans vertically concatenated graphs in altair?

所以,我设法使用 altair 绘制了这些垂直连接的图表。我的问题是,如何绘制一条横跨所有三个图表的垂直线(例如,得分 20)?

我将post数据和代码画出下图:

数据:

    score   population_pct  conversion_rate geb_income
0   10  39.6    0.1 0.1
1   20  0.8 1.9 0.2
2   30  1.8 6.0 0.9
3   40  3.9 9.1 3.1
4   50  7.2 11.9    6.7
5   60  10.5    15.8    12.6
6   70  12.6    22.5    20.0
7   80  12.5    31.8    26.4
8   90  9.6 48.2    27.0
9   100 1.4 57.0    3.0

您可以通过复制 (Ctrl+C) 数据并执行此代码来复制它:

import pandas as pd
import altair as alt

metrics_by_score = pd.read_clipboard()

metrics_by_score_base = alt.Chart(metrics_by_score).mark_bar(size=30).encode(x = 'score').properties(width=800, height=100)

population = metrics_by_score_base.mark_bar(size=30).encode(y = 'population_pct')

conversion_rate = metrics_by_score_base.mark_bar(size=30, color='red').encode(y = 'conversion_rate')

geb_income = metrics_by_score_base.mark_bar(size=30, color='black').encode(y = 'geb_income')

population_labels = population.mark_text(dy=-10).encode(text='population_pct')
conversion_rate_labels = conversion_rate.mark_text(dy=-10).encode(text='conversion_rate')
geb_income_labels = geb_income.mark_text(dy=-10).encode(text='geb_income')

alt.vconcat(population + population_labels, conversion_rate + conversion_rate_labels, geb_income + geb_income_labels)

有没有办法将这条线变成可拖动的元素,以便我可以沿 x 轴移动它?

这不是您想要的(通常 Altair 不允许您在各个方面画线),但这里有一些大致相同的东西:

import altair as alt
import pandas as pd

with open('data.csv', 'w') as f:
  f.write("""
    score   population_pct  conversion_rate geb_income
0   10  39.6    0.1 0.1
1   20  0.8 1.9 0.2
2   30  1.8 6.0 0.9
3   40  3.9 9.1 3.1
4   50  7.2 11.9    6.7
5   60  10.5    15.8    12.6
6   70  12.6    22.5    20.0
7   80  12.5    31.8    26.4
8   90  9.6 48.2    27.0
9   100 1.4 57.0    3.0
""")

data = pd.read_csv('data.csv', sep='\s+')
data = data.melt('score')

bars = alt.Chart().mark_bar(size=30).encode(
  x='score:Q',
  y=alt.Y('value', title=None)
).properties(width=800, height=100)

text = bars.mark_text(dy=-10).encode(
  text='value'
)

overlay = pd.DataFrame({'x': [25]})
vline = alt.Chart(overlay).mark_rule(color='red', strokeWidth=3).encode(x='x:Q')

alt.layer(bars, text, vline, data=data).facet(
  row='variable'
)