在python Altair图的热图中添加间距

时间:2019-07-21 23:00:21

标签: python altair

是否可以在Altair python图中使用mark_rect()创建的热图中添加一些间距?图1中的热图将转换为图2中的热图。您可以假定它来自dataframe,并且每一列都对应一个变量。我故意这样画白条,以避免任何硬编码的索引解决方案。基本上,我正在寻找一种解决方案,可以提供列名和/或索引名以获取垂直和/或水平绘制的白色间距。

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

创建这些波段的一种方法是使用自定义仓位对图表进行分面。这是一种使用pandas.cut创建垃圾箱的方法。

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
)

enter image description here

请注意,resolve_scale(x='independent')不要在每个小平面上重复轴,而spacing中的configure_facet参数可以控制间距的宽度。我在标头中设置了labelFontSize=0,以便在每个构面的顶部都看不到容器名称。

答案 1 :(得分:0)

您可以使用scale.bandPaddingInner配置参数来指定热图内的间距,该参数是介于0和1之间的数字,该数字指定应填充的矩形标记的分数,默认值为零。例如:

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
)

enter image description here