Altair: adding sorting destroys chart

Viewed 44

The following code produces a column chart in which the y axis grows in the wrong direction.

alt.Chart(df).mark_line().encode(
    x = alt.X('pub_date', timeUnit='month'),
    y = alt.Y('sum(has_kw)',  ),
)

enter image description here

I wanted to correct it as suggested by https://stackoverflow.com/a/58326269, and changed my code to

alt.Chart(df).mark_line().encode(
    x = alt.X('pub_date', timeUnit='month'),
    y = alt.Y('sum(has_kw)', sort=alt.EncodingSortField('y', order='descending') ),
)

But now altair produces a strange diagram, see 2.

here

That is, sum(has_kw) is calculated wrong. Why this, and how to correct it?

1 Answers

It is hard to know exactly without seeing a sample of your data but you could try one of the following (based on the example you linked). This first approach is similar to what you tried already:

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(0, 3), range(0, 3))
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='descending'),
    color='z:Q'
)

enter image description here

This second approaches simply reverses the axes without sorting it and might be more compatible with your data:

alt.Chart(source).mark_rect().encode(
    x='x:O',
    y=alt.Y('y:O', scale=alt.Scale(reverse=True)),
    color='z:Q'
)

enter image description here

Related