Adding spacing in heatmaps of python altair plots

允我心安 提交于 2019-12-13 15:17:11

问题


Is it possible to add some spacing in the heatmaps created by using mark_rect() in Altair python plots? The heatmap in figure 1 will be converted to the one in figure 2. You can assume that this is from a dataframe and each column corresponds to a variable. I deliberately drew the white bars like this to avoid any hardcoded indexed solution. Basically, I am looking for a solution where I can provide the column name and/or the index name to get white spacings drawn both vertically and/or horizontally.


回答1:


You can specify the spacing within heatmaps using the scale.bandPaddingInner configuration parameter, which is a number between zero and one that specifies the fraction of the rectangle mark that should be padded, and defaults to zero. 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='y:O',
    color='z:Q'
).configure_scale(
    bandPaddingInner=0.1
)




回答2:


One way to create these bands would be to facet the chart using custom bins. Here is a way to do that, using pandas.cut to create the bins.

import pandas as pd
import altair as alt

df = (pd.util.testing.makeDataFrame()
      .reset_index(drop=True)  # drop string index
      .reset_index()  # add an index column
      .melt(id_vars=['index'], var_name="column"))

# To include all the indices and not create NaNs, I add -1 and max(indices) + 1 to the desired bins.
bins= [-1, 3, 9, 15, 27, 30]
df['bins'] = pd.cut(df['index'], bins, labels=range(len(bins) - 1))
# This was done for the index, but a similar approach could be taken for the columns as well.

alt.Chart(df).mark_rect().encode(
    x=alt.X('index:O', title=None),
    y=alt.Y('column:O', title=None),
    color="value:Q",
    column=alt.Column("bins:O", 
                      title=None, 
                      header=alt.Header(labelFontSize=0))
).resolve_scale(
    x="independent"           
).configure_facet(
    spacing=5
)

Note the resolve_scale(x='independent') to not repeat the axis in each facet, and thhe spacing parameter in configure_facet to control the width of the spacing. I set labelFontSize=0 in the header so that we do not see the bins names on top of each facet.



来源:https://stackoverflow.com/questions/57137594/adding-spacing-in-heatmaps-of-python-altair-plots

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!