Altair - 负和正不同颜色的面积图 [英] Altair - Areaplot with different colours for negative and positive

查看:47
本文介绍了Altair - 负和正不同颜色的面积图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Pandas DataFrames 中有一个包含正值和负值的列,我需要为正负 y 轴制作一个具有不同颜色的区域图.

I have a column in my pandas DataFrames with positive and negative values, I need to make an area graph with different colours for positive and negative y axis.

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

So far, I am not able to do that with 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

如何制作正负不同颜色的图?

How can I make the are plot with different colours for positive and negative?

推荐答案

你可以这样做:

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'
)

一些注意事项:

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

  • we use a calculated color encoding rather than a color condition because an encoding will actually split the data into two groups, which is required for area marks (area marks, unlike point marks, draw a single chart element for each group of data, and a single chart element cannot have multiple colors)

yimpute 参数很重要,因为它告诉每个组将未定义的值视为零,而另一个组已定义.这可以防止在组中的点之间绘制一条直线的奇怪伪影.

The impute argument to y is important because it tells each group to treat the value as zero where it is undefined and the other group is defined. This prevents strange artifacts where a straight line is drawn between points in the group.

这篇关于Altair - 负和正不同颜色的面积图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆