python - 覆盖 Altair 折线图的默认分组?

标签 python altair

我想制作一张图表,其中一条线在沿线的不同位置具有不同的颜色。

这不起作用:

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

chart

(我想要一条连续的线,而不是一堆线段。)

问题大概是 Altair(或 Vega-Lite)决定按颜色分组并为每个组绘制一条单独的线。

我可以覆盖此默认分组以表示整行应该是一个组吗?

为了比较,在 R 的 ggplot2 库中 the group argument would do what I'm 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')

这种方法放弃告诉 Altair/Vega-Lite 我希望我的点组成一条线,而是通过使用额外的(移位的)数据副本在每对点之间创建一个单独的线段。

线段根据每个线段的左侧点进行着色,我认为这有点误导(如果只有几个点,则非常误导)。您可以通过将颜色设置为两侧的平均值来使黑客变得更加复杂。

enter image description here

仍然希望有人能明确回答用户是否可以控制分组。

关于python - 覆盖 Altair 折线图的默认分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59844077/

相关文章:

python - 属性错误: 'str' object has no attribute get

python - 如何在 Altair Visual 中的 Y 轴和条形图之间添加更多空间

python - 类型错误 : to_list_if_array() got an unexpected keyword argument 'convert_dtype'

python - 将 alt.Chart() 与来自 google drive url 链接的数据一起使用

python - 在单列上使用 `apply` 加速分组

java - 使用java方法计算python中列表的所有子集

python - 将参数从函数传递到类方法

python - 将列表拆分为总和大致相等的 N 个子列表

python - Altair 更改边框颜色 LayerChart

python - 移动浏览器 Vega-Lite 规范中的间隔选择