简体   繁体   中英

override altair's default grouping for line chart?

I'd like to make a chart with one line with different colors at different spots along the line.

This doesn't work:

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

x = np.linspace(0,1)
y = x**2
c = np.round(x*20)
df = pd.DataFrame({'x': x, 'y': y, 'c': c})
print(df.head())
alt.Chart(df).mark_line().encode(x='x', y='y', color='c')

图表

(I want one continuous line, not a bunch of segments.)

Presumably the problem is that Altair (or Vega-Lite) decided to group by color and draw a separate line for each group.

Can I override this default grouping to say that the entire line should be a single group?

For comparison, in R's ggplot2 library the group argument would do what I'm looking for .

Here's a hack to get basically the plot I was looking for:

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

x = np.linspace(0,1)
y = x**2
c = np.round(x*20)
df = pd.DataFrame({'x': x, 'y': y, 'c': c})
df_shifted = df.shift()
df_shifted['c'] = df['c']
alt.Chart(pd.concat([df, df_shifted])).mark_line().encode(x='x', y='y', color='c')

This approach gives up on telling Altair/Vega-Lite that I want my points to make up a single line, and instead makes one separate segment between every pair of points by using an extra (shifted) copy of the data.

The line segment is colored based on the left point in each segment, which I guess is a little misleading (very misleading if there were only a few points). You could make the hack more complicated by making the color the average of the two sides.

在此处输入图片说明

Still hoping someone will answer definitively on whether the user can control the grouping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM