python-3.x - 如何将一个盒子形状的图层添加到 Altair 图中?

标签 python-3.x altair

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

最佳答案

我建议用一个折线图绘制所有四个边。然后您可以使用 domain scale 参数来调整轴限制(更多信息请参见 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

关于python-3.x - 如何将一个盒子形状的图层添加到 Altair 图中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55015304/

相关文章:

python - 如何在遵循 pylint 规则的同时格式化长字符串?

python - 如何使用 Altair 在散点图中突出显示标记?

resize - 我如何 .add_selection(interval) 并将间隔绑定(bind)到 Altair 中同一图表上的 alt.X(domain=interval)?

vega-lite - 使 Vega-Lite 条形标记相邻

python - Altair:如何在条形图中包含没有数据的值的位置

python - 标识符规范化 : Why is the micro sign converted into the Greek letter mu?

python - 字符串列表中字符串出现的双重列表理解

python - 如何动态打开json文件?

python - 如何删除作为短信发送的 "[Attachment(s) removed]"字符串?

python - 更改 Altair 图中的图例编号范围