简体   繁体   中英

Altair: How to align axis in layered plot?

I'm trying to create an overlay plot of a binary grid map and a simple line plot. However, when creating a layered plot, the axis are not aligned and the plot becomes unreadable. Ideally, I'd like to have both plot share a single axis so that the line coordinates match the map coordinates.

Here's a basic snippet of my attempt:

import torch as th
import altair as alt
import pandas as pd

xv, yv = th.meshgrid(th.linspace(-10, 10, 100), th.linspace(-10, 10, 100))
o_map = th.zeros_like(xv)
o_map[40:60, 40:60] = 1  # add obstacle centred on origin
map_df = pd.DataFrame(
    {"x": xv.flatten(), "y": yv.flatten(), "z": o_map.flatten()}
)
map_chart = (
    alt.Chart(map_df)
    .mark_rect()
    .encode(
        x=alt.X("x:O", axis=alt.Axis(format=".2")),
        y=alt.Y("y:O", axis=alt.Axis(format=".2")),
        color="z:N",
    )
    .properties(width=500, height=500)
)

x = th.linspace(-5, 10, 100)
line_df = pd.DataFrame({"x": x, "y": 0.2 * x ** 2 - 3})
line_chart = alt.Chart(line_df).mark_line(color="red").encode(x="x:Q", y="y:Q")

layer_chart = map_chart + line_chart

The resulting plots are as following:

Line plot

Binary map

Layered plot

If you change the x and y channel data type in map_chart from 'O' to 'Q' the axis should be aligned automatically.

...
map_chart = (
    alt.Chart(map_df)
    .mark_rect()
    .encode(
        x=alt.X("x:Q"),
        y=alt.Y("y:Q"),
        color="z:N",
    )
    .properties(width=500, height=500)
)
...
  • Update: use mark_square instead of mark_rect

It seems that quantitative data type doesn't play very well when marker is rect (eg referring to the official example here , if you change the type of x and y to quantitative , the heatmap doesn't look right, see below). 在此处输入图片说明

So if rect is not a must-have marker, I would suggest you choose square . As long as your grid is dense enough and the marker size is large enough there won't be empty gaps left between markers, effectively what you want. 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM