【问题标题】:How do I add a layer in a shape of a box to an altair plot?如何将一个盒子形状的图层添加到 altair 图中?
【发布时间】:2019-07-27 15:47:38
【问题描述】:

我正在尝试使用带有坐标的熊猫数据框添加一个用作打击区的框,并将其传递给 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 轴,使框周围有一点边距?

【问题讨论】:

    标签: python-3.x altair


    【解决方案1】:

    我建议使用单个折线图绘制所有四个边。然后,您可以使用 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'
    )
    

    或者,您可以使用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'
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-20
      • 2020-07-23
      • 2012-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-29
      相关资源
      最近更新 更多