我想作一个绘图,在其中我遮挡两条曲线之间的区域,颜色取决于哪条曲线较高(例如,如果“曲线1”高于“曲线”,则曲线之间的区域为绿色) 2”,如果“曲线1”低于“曲线2”,则为红色)。以下情节是我做出此类情节的最大努力。结果接近我想要的结果,但是有一个问题,当我不希望这样做时,它会将具有相同符号的区域连接起来。 (最明显的例子是将“ x〜0.6”连接到“ x〜1.1”的绿色区域。)是否有更好的方法绘制这样的图?
import altair as alt
import numpy as np
import pandas as pd
df = pd.DataFrame({
'x': np.linspace(0, 2, 100),
})
df['y1'] = np.sin(2 * np.pi * df.x)
df['y2'] = np.cos(2 * np.pi * df.x)
df['c'] = (df.y1 > df.y2).apply(lambda b: 'darkseagreen' if b else 'indianred')
base_chart = alt.Chart(df, width=1.618 * 400, height=400)
l1 = base_chart.mark_line(stroke='green', strokeWidth=4).encode(
x='x:Q',
y=alt.Y('y1:Q', axis=alt.Axis(title='y')),
)
l2 = base_chart.mark_line(stroke='red', strokeWidth=4).encode(
x='x:Q',
y='y2:Q',
)
a = base_chart.mark_area().encode(
x='x:Q',
y='y1:Q',
y2='y2:Q',
fill=alt.Color('c:N', scale=None),
)
alt.layer(a, l1, l2)
答案 0 :(得分:1)
我发现我可以使用impute
来防止在区域之间绘制不必要的线条。
import altair as alt
import numpy as np
import pandas as pd
df = pd.DataFrame({
'x': np.linspace(0, 2, 100),
})
df['y1'] = np.sin(2 * np.pi * df.x)
df['y2'] = np.cos(2 * np.pi * df.x)
df['c'] = (df.y1 > df.y2).apply(lambda b: 'darkseagreen' if b else 'indianred')
base_chart = alt.Chart(df, width=1.618 * 400, height=400)
l1 = base_chart.mark_line(stroke='green', strokeWidth=4).encode(
x='x:Q',
y=alt.Y('y1:Q', axis=alt.Axis(title='y')),
)
l2 = base_chart.mark_line(stroke='red', strokeWidth=4).encode(
x='x:Q',
y='y2:Q',
)
a = base_chart.mark_area().encode(
x='x:Q',
y=alt.Y('y1:Q', impute={'value': None}),
y2='y2:Q',
fill=alt.Color('c:N', scale=None),
)
alt.layer(a, l1, l2)