因此,我设法使用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轴移动?
答案 0 :(得分:3)
这并不是您想要的(通常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'
)