How to explicitly set y-range for mark_rect (heat map)

Viewed 528

I'm plotting heat maps for many sites using the output of groupby(['Month','Year']

Cells (month/year) that have no value are shown as blank-- which is good.

The 'problem' is that I'd like the full year of data (Jan-Dec) to always be shown. However for datasets without any data at the starting or ending months of the year, the data are plotted without showing those parts of the the grid. This also changes the sizes of the cells when fewer months are shown.

That is, I'd like each plot to have the same structure as:

enter image description here

Rather than reducing to something like this:

enter image description here

For consistency, I'd prefer to have the grid remain the same (months 1-12) for every plot even if it leaves empty space at the top (start of year) or bottom (end of year).

I tried setting the 'y' and 'y2' params listed in the mark_rect description to force it to always show the y-range from 1-12 but it had no effect.

1 Answers

You can specify a scale domain including the values you want to show (months from 1 to 12):

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

np.random.seed(0)
df = pd.DataFrame({
    'date': pd.date_range('2010-01-01', periods=120, freq='M'),
    'value': np.random.rand(120),
})
df = df[(df.value > 0.3) & (df.date.dt.month < 8)]

alt.Chart(df).mark_rect().encode(
    x='year(date):O',
    y=alt.Y('month(date):O', scale=alt.Scale(domain=list(range(1, 13)))),
    color='value:Q'
)

enter image description here

Note that you'll have to view this using Vega-Lite 4.9 or newer, as there is a bug in earlier vega-lite versions that prevents the values from being correctly displayed. If you're using Jupyter notebook, click the (⋯) menu in the upper right and choose Open in Vega Editor.

Related