Search code examples
pythonvegavega-litealtair

Broken axis in Altair/Vega


I have a Normalized Stacked Area Chart with huge differences between one variable and the others like:

df1=pd.DataFrame.from_dict(
    {'YEAR': {0: 2010,
      1: 2010,  2: 2010,  3: 2010,  4: 2011,  5: 2011,  6: 2011,  7: 2011,
      8: 2012,  9: 2012,  10: 2012,  11: 2012,  12: 2013,  13: 2013,  14: 2013,  15: 2013},
     'impact_FU': {0: 0.031479085164086554,  1: 5.9856927170853295e-05,  2: 1.1035885271638534e-05,  3: 5.8233509026863169e-06,
      4: 0.059176271387395112,  5: 0.00011179170132430088,  6: 1.9783914536689014e-05,  7: 1.0670218804040578e-05,
      8: 0.083935088170893221,  9: 0.00014806339884972569,  10: 2.3424374354037232e-05,  11: 1.30716950360811e-05,
      12: 0.10678138273474649,  13: 0.00016610749233828763,  14: 2.4764766148334989e-05,
      15: 1.3509464279754472e-05},
     'proc': {0: 'biogenic',  1: 'harvesting',  2: 'planting',  3: 'tending',
      4: 'biogenic',  5: 'harvesting',  6: 'planting',  7: 'tending',
      8: 'biogenic',  9: 'harvesting',  10: 'planting',  11: 'tending',
      12: 'biogenic',  13: 'harvesting',  14: 'planting',  15: 'tending'},
     'scenario': {0: 'BAU45',  1: 'BAU45',  2: 'BAU45',  3: 'BAU45',  4: 'BAU45',  5: 'BAU45',  6: 'BAU45',
      7: 'BAU45',  8: 'BAU45',  9: 'BAU45',  10: 'BAU45',  11: 'BAU45',  12: 'BAU45',  13: 'BAU45', 
                  14: 'BAU45',  15: 'BAU45'}})

Chart(df1).mark_area(stacked='normalize').encode(
    X('YEAR:T', timeUnit='year',),
    Y('sum(impact_FU)'),
    color=Color('proc:N'),
)

Is there any way in Altair/vega-lite/Vega to make broken y-axys...something like this?


Solution

  • Since you have very different value ranges for your data column, you can use a log scale transformation as follows. Altair comes with many scale transformations, and in your case, you'd use alt.Scale(type='log')

    alt.Chart(df1).mark_area().encode(
        alt.X('YEAR:O'), 
        alt.Y('impact_FU', scale=alt.Scale(type='log')),
        color='proc:N',
    )
    

    which produces:

    Area plot with log scale

    Altair is great for Facet charts, so you can keep the log scale and also facet on each proc with just one single extra line of code:

    alt.Chart(df1).mark_area().encode(
        alt.X('YEAR:O'), 
        alt.Y('impact_FU', scale=alt.Scale(type='log')),
        color='proc:N',
        column='proc:N'
    )
    

    to get:

    Facet plot in Altair