Altair - Areaplot with different colours for negative and positive

独自空忆成欢 提交于 2021-01-29 10:49:40

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/58776946/altair-areaplot-with-different-colours-for-negative-and-positive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!