如何在高空绘图中以盒子形状添加图层?

时间:2019-03-06 03:55:15

标签: python-3.x altair

我正在尝试使用带有坐标的熊猫数据框添加一个框用作罢工区,并将其传递给altair。

box = pd.DataFrame()
box.loc[:,"x"] = [-0.5, 0.5, 0.5, -0.5]
box.loc[:,'y'] = [1.25, 1.25, 0.5, 0.5]

我尝试了以下方法:

g = alt.Chart(box.loc[0:1,:]).mark_line().encode(
x = 'x',
y = 'y')

d = alt.Chart(box.loc[1:2,:]).mark_line().encode(
x = 'x',
y = 'y')

e = alt.Chart(box.loc[2:3,:]).mark_line().encode(
x = 'x',
y = 'y')

f = alt.Chart(box.loc[3:4,:]).mark_line().encode(
x = 'x',
y = 'y')

g + d + e + f

我还想知道如何调整x和y轴,以便在盒子周围留一点空白?

1 个答案:

答案 0 :(得分:2)

我建议用一个折线图绘制所有四个侧面。然后,您可以使用domain比例参数来调整轴限制(请参阅Altair文档的Adjusting Axis Limits部分)。

这里是一个例子:

import altair as alt
import pandas as pd

box = pd.DataFrame({
    'x': [-0.5, 0.5, 0.5, -0.5, -0.5],
    'y': [1.25, 1.25, 0.5, 0.5, 1.25]
}).reset_index()


alt.Chart(box).mark_line().encode(
    alt.X('x', scale=alt.Scale(domain=(-1, 1))),
    alt.Y('y', scale=alt.Scale(domain=(0, 1.5))),
    order='index'
)

enter image description here

或者,您可以使用rect标记来避免必须以正确的顺序手动构造矩形的坐标:

box = pd.DataFrame({'x1': [-0.5], 'x2': [0.5], 'y1': [0.5], 'y2': [1.25]})

alt.Chart(box).mark_rect(fill='none', stroke='black').encode(
    alt.X('x1', scale=alt.Scale(domain=(-1, 1))),
    alt.Y('y1', scale=alt.Scale(domain=(0, 1.5))),
    x2='x2',
    y2='y2'
)

enter image description here