Karim
Karim

Reputation: 529

Why is the y-axis upside down on Altair heatmaps and how to reverse it?

Looking at the basic heatmap example from Altair, I noticed that the y-axis is reversed. 1) is there any particular reason for that? 2) how can I reverse it?

I tried looking through the documentation but have been unable to find how to manipulate the axes in order to reverse the y-axis.

Upvotes: 1

Views: 1025

Answers (1)

jakevdp
jakevdp

Reputation: 86433

You can use the sort property of the y encoding to change the default sort order. For example:

import altair as alt
import numpy as np
import pandas as pd

# Compute x^2 + y^2 across a 2D grid
x, y = np.meshgrid(range(-5, 5), range(-5, 5))
z = x ** 2 + y ** 2

# Convert this grid to columnar data expected by Altair
source = pd.DataFrame({'x': x.ravel(),
                     'y': y.ravel(),
                     'z': z.ravel()})

alt.Chart(source).mark_rect().encode(
    x='x:O',
    y=alt.Y('y:O',
        sort=alt.EncodingSortField('y', order='descending')),
    color='z:Q'
)

enter image description here

Upvotes: 3

Related Questions