2

这是我之前关于 Altair Ridgeline 情节的问题的延伸。

我有一个这样创建的情节:

import pandas as np
import numpy as np

source = pd.DataFrame(columns=list('ab'))
source['a'] = np.random.randint(0,17,size=500)
source['color'] = source['a'].apply(lambda x: 'blue' if x < 10 else 'red'] 
source['a'] = source['a'].astype('str')
source['b'] = np.random.randint(1000,5000,size=500).astype('float')


import altair as alt

step = 20
overlap = 1

alt.Chart(source, height=step).transform_joinaggregate(
    mean_temp='mean(b)', groupby=['a']
).transform_bin(
    ['bin_max', 'bin_min'], 'b'
).transform_aggregate(
    value='count()', groupby=['a', 'b', 'bin_min', 'bin_max']
).transform_impute(
    impute='value', groupby=['a', 'b'], key='bin_min', value=0
).mark_area(
    interpolate='monotone',
    fillOpacity=0.8,
    stroke='lightgray',
    strokeWidth=0.5
).encode(
    alt.X('bin_min:Q', bin='binned', title=''),
    alt.Y(
        'value:Q',
        scale=alt.Scale(range=[step, -step * overlap]),
        axis=None
    ),
    alt.Fill(
        'b:Q',
        legend=None,
    )
).facet(
    row=alt.Row(
        'a:N',
        title=None,
        header=alt.Header(labelAngle=0, labelAlign='right')
    )
).properties(
    title='',
    bounds='flush'
).configure_facet(
    spacing=0
).configure_view(
    stroke=None
).configure_title(
    anchor='end'
)

我的问题是如何使绘图的行具有不同的颜色(“蓝色”或“红色”取决于数据框中的“颜色”列)?我尝试使用alt.Scale(domain='color:N')in alt.Fill()color='color:N'param in配置它,encode()但它不起作用。分面标题标签也应该是彩色的。

4

1 回答 1

1

您可以通过将填充或颜色编码设置为"color"具有原始比例的列来完成此操作。

也就是说,您已经根据"b"列设置了颜色编码,因此您需要对这些信息进行不同的编码;例如,您可以改用不透明度。

这是将这些放在一起的示例:

import pandas as np
import numpy as np

source = pd.DataFrame(columns=list('ab'))
source['a'] = np.random.randint(0,17,size=500)
source['color'] = source['a'].apply(lambda x: 'blue' if x < 10 else 'red')
source['a'] = source['a'].astype('str')
source['b'] = np.random.randint(1000,5000,size=500).astype('float')


import altair as alt

step = 20
overlap = 1

alt.Chart(source, height=step).transform_joinaggregate(
    mean_temp='mean(b)', groupby=['a']
).transform_bin(
    ['bin_max', 'bin_min'], 'b'
).transform_aggregate(
    value='count()', groupby=['a', 'b', 'bin_min', 'bin_max', 'color']
).transform_impute(
    impute='value', groupby=['a', 'b', 'color'], key='bin_min', value=0
).mark_area(
    interpolate='monotone',
    fillOpacity=0.8,
    stroke='lightgray',
    strokeWidth=0.5
).encode(
    alt.X('bin_min:Q', bin='binned', title=''),
    alt.Y(
        'value:Q',
        scale=alt.Scale(range=[step, -step * overlap]),
        axis=None
    ),
    alt.Fill('color:N', scale=None),
    alt.Opacity(
        'b:Q',
        legend=None,
    )
).facet(
    row=alt.Row(
        'a:N',
        title=None,
        header=alt.Header(labelAngle=0, labelAlign='right')
    )
).properties(
    title='',
    bounds='flush'
).configure_facet(
    spacing=0
).configure_view(
    stroke=None
).configure_title(
    anchor='end'
)

在此处输入图像描述

于 2021-01-23T16:10:52.480 回答