Mikele
Mikele

Reputation: 91

How to shift intersection point of x- and y-axis from 0 to 1 using Python Altair?

I have a dashboard, in which you can select several datasets using a widget. I am using the Altair library in Python to make classical line graphs from these datasets with both x-and y-axis starting at zero. The displayed data are normalized data, meaning all datasets start at the y-value=1 by definition. As the datasets represent different parameters the y-axis changes dynamically from dataset to dataset. The graph is coded roughly like the following:

chart = alt.Chart(df_datapoints).mark_line().encode(
        x=alt.X('X-Value',axis=alt.Axis(title='X-Values', tickCount=10)),
        y=alt.Y('Y-Value', axis=alt.Axis(title='Normalized to Baseline')),
        color=alt.Color('Test ID', legend=None)
        )

The graph looks then like this:

enter image description here

Now I would like to have the x-axis starting at y-value=1 to better see which values increase or decrease from the starting point. Is there a possibility to shift the starting point of the x-axis in this simple line graph from from zero to 1? I haven't found anything in the Altair Documentation. Or would it be possible to add a strong line at Y=1 to see the normalized baseline?

Upvotes: 2

Views: 1264

Answers (1)

jakevdp
jakevdp

Reputation: 86433

One way to do this is to use the axis.offset property, which controls the offset of the axes in pixels. You'll have to adjust this depending on the bounds of your data if you want the axes to intersect at a particular data point:

import altair as alt
import pandas as pd

df = pd.DataFrame({
    'x': [0, 1, 2, 3, 4],
    'y': [0, 1, 2, 3, 4],
})

alt.Chart(df).mark_line().encode(
  x=alt.X('x', axis=alt.Axis(grid=False, offset=-75)),
  y=alt.Y('y', axis=alt.Axis(grid=False, offset=-100))
)

enter image description here

Upvotes: 2

Related Questions