3

因此,我设法使用 altair 绘制了这些垂直连接的图表。我的问题是,我怎样才能画一条跨越所有三个图表的垂直线(例如,得分 20)?

在此处输入图像描述

我将发布数据和代码以绘制下图:

数据:

    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 轴移动它?

4

1 回答 1

5

这并不完全符合您的要求(通常 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'
)

在此处输入图像描述

于 2019-02-20T21:52:29.630 回答