Reputation: 9945
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.
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?
Upvotes: 0
Views: 1639
Reputation: 86310
You could do something like this:
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'
)
Some notes:
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)
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.
Upvotes: 2