Search code examples
pythonaltair

Altair chart axis is not scaling well with small float numbers like matplotlib


How can I get Altair to plot the line in the same way as matplotlib (first image) without displaying ranges 0.00 to 0.06 in y axis? See code and example below:

import pandas as pd
import altair as alt

loss_data = [0.07727576792240143, 0.0697188749909401, 0.06957338005304337, 0.06949638575315475, 0.06944674998521805, 0.06940694153308868, 0.06925933063030243, 0.06923820823431015, 0.06922164559364319, 0.06911467760801315, 0.0691060945391655, 0.0690980926156044, 0.06901008635759354, 0.06900542229413986, 0.0689304992556572, 0.06892699748277664, 0.06892561912536621, 0.068858303129673, 0.06885731965303421, 0.06880014389753342, 0.0687987431883812, 0.06874748319387436, 0.06874550133943558, 0.06870073080062866, 0.06869713962078094, 0.06869688630104065, 0.06865549832582474, 0.0686517134308815, 0.06861335039138794, 0.0686088502407074, 0.06857530772686005, 0.06856919080018997, 0.0685390755534172, 0.06853235512971878, 0.06850989162921906, 0.06850464642047882, 0.06850180774927139, 0.0684986561536789, 0.06849765032529831, 0.06849698722362518]

loss_df = pd.DataFrame(loss_data, columns=["loss"])
loss_df.insert(0, 'iteration', range(1, 1 + len(loss_df)))
loss_df

loss_df["loss"].plot(title="Training loss")

alt.Chart(loss_df, title="Training loss").mark_line().encode(
  x=alt.X("iteration", scale=alt.Scale(domain=[0, 40])),
  y=alt.Y("loss",)
)

matplotlib

altair


Solution

  • You need scale=alt.Scale(zero=False), like so:

    alt.Chart(loss_df, title="Training loss").mark_line().encode(
       x=alt.X("iteration", scale=alt.Scale(domain=[0, 40])),
       y=alt.Y("loss",scale=alt.Scale(zero=False))
    )