Altair - 具有不同颜色的负值和正值区域图
Altair - Areaplot with different colours for negative and positive
我的 pandas DataFrames 中有一列具有正值和负值,我需要为正负 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
我怎样才能用不同颜色的正面和负面的曲线图?
你可以这样做:
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'
)
一些注意事项:
我们使用计算的颜色编码而不是颜色条件,因为编码实际上会将数据分成两组,这是区域标记所必需的(区域标记与点标记不同,绘制单个每组数据的图表元素,单个图表元素不能有多种颜色)
y
的 impute
参数很重要,因为它告诉每个组将未定义的值视为零,而另一个组已定义。这可以防止在组中的点之间绘制一条直线的奇怪伪像。
我的 pandas DataFrames 中有一列具有正值和负值,我需要为正负 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
我怎样才能用不同颜色的正面和负面的曲线图?
你可以这样做:
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'
)
一些注意事项:
我们使用计算的颜色编码而不是颜色条件,因为编码实际上会将数据分成两组,这是区域标记所必需的(区域标记与点标记不同,绘制单个每组数据的图表元素,单个图表元素不能有多种颜色)
y
的impute
参数很重要,因为它告诉每个组将未定义的值视为零,而另一个组已定义。这可以防止在组中的点之间绘制一条直线的奇怪伪像。