pythonaltairpolynomials

facet figure - polynomial + linear in Altair


I want to make a facet figure with Linear and Polynomial regression in Altair. Stacking together scatter and regression plots seems understandable. However, adding additional polynomial analysis seems problematic. I cannot display the result. I was trying to go around by making a degree list for 1, 3, and 5 as in Altair Gallery, and I was unsuccessful again.

Can you help me understand the issue?

Here is my data snippet:

years = list(range(2024, 2051))
rcp_scenarios = ['RCP2.6', 'RCP4.5', 'RCP6.0', 'RCP8.5']
data = {"YEAR": years} 
for rcp in rcp_scenarios:
   data[rcp] = np.random.uniform(low=500, high=2000, size=len(years))
df = pd.DataFrame(data)
df_melted = pd.melt(df, id_vars=["YEAR"], value_vars=rcp_scenarios, 
                        var_name="RCP", value_name="RR")

And here is my Altair snippet:

scatter = alt.Chart(All_RCP_Df_yearly).mark_circle(size=60, opacity=0.60).encode(
    x=alt.X('YEAR'),
    y=alt.Y('RR', title="Annual Precipitation [mm]"),
    color='RCP',
    tooltip=['YEAR', 'RR', 'RCP'])

linear_regression = alt.Chart(All_RCP_Df_yearly).transform_regression(
    'YEAR', 'RR', method='linear', groupby=['RCP']
).mark_line(opacity=0.75).encode(
    x='YEAR',
    y='RR',
    color='RCP')

polynomial_regression = alt.Chart(All_RCP_Df_yearly).transform_regression(
    'YEAR', 'RR', method='poly', order=2, groupby=['RCP']
).mark_line(opacity=0.75, strokeDash=[5, 3]).encode(
    x='YEAR',
    y='RR',
    color='RCP')

chart = scatter + linear_regression + polynomial_regression

chart = chart.facet(
    columns=2,
    facet=alt.Facet('RCP'))

chart.display()

Solution

  • When I run your code (after changing the plotted df to df_melted instead of the undefined variable and adding .scale(zero=False) to the x-axis), I get the chart below. It looks to me like both regression lines are working, could you elaborate on the issue you are experiencing?

    enter image description here