Altair-带有正负不同颜色的Areaplot

时间:2019-11-09 06:24:48

标签: python visualization altair

我的pandas DataFrames中有一列带有正值和负值的列,我需要制作一个带有不同颜色的y和Y轴面积图。

到目前为止,我无法使用alt.condition来做到这一点

brush = alt.selection(type='interval', encodings=['x'])

upper = alt.Chart(yData['plotY'].fillna(0).reset_index()[24000:26000],
                  title = '_name').mark_area().encode(x = alt.X('{0}:T'.format(yData['plotY'].index.name),
                                                                scale = alt.Scale(domain=brush)),
                                                      y = 'plotY',
#                                                       color=alt.condition(
#                                                             alt.datum.plotY > 0,
#                                                             alt.value("steelblue"),  # The positive color
#                                                             alt.value("orange")  # The negative color
#                                                         ),
                                                      tooltip=['plotY']).properties(width = 700,
                                                                                  height = 230)

lower = upper.copy().properties(
    height=20
).add_selection(brush)

p = alt.vconcat(upper, lower).configure_concat(spacing=0)
p

Graph

我怎样才能使正方图和负方图使用不同的颜色?

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

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

x = np.linspace(0, 100, 1000)
y = np.sin(x)
df = pd.DataFrame({'x': x, 'y': y})

alt.Chart(df).transform_calculate(
    negative='datum.y < 0'
).mark_area().encode(
    x='x',
    y=alt.Y('y', impute={'value': 0}),
    color='negative:N'
)

enter image description here

一些注意事项:

  • 我们使用计算的颜色编码而不是颜色条件,因为编码实际上会将数据分为两组,这对于区域标记来说是必需的(区域标记与点标记不同,为每个区域绘制一个图表元素一组数据,并且一个图表元素不能具有多种颜色

  • impute的{​​{1}}参数很重要,因为它告诉每个组在未定义且定义了另一个组的情况下将该值视为零。这样可以防止在组中的点之间绘制直线的奇怪伪像。