pythonpandasseabornseaborn-objects

Discrete date values for x-axis in seaborn.objects plot


I am trying to prepare a bar plot using seaborn.objects with time series data where the x-axis ticks and labels are only on the dates that really appear in the data.

import pandas as pd
import seaborn.objects as so
df1 = pd.DataFrame({'date': pd.to_datetime(['2022-01-01', '2022-02-01']), 'val': [10,20,]})
so.Plot(df1, x='date', y='val').add(so.Bar())

The result is the following graph with a tick mark at 2022-01-15. Going to three entries in the dataframe solves the issue, but how would I do it in the presented case.

Adding .scale(x=so.Nominal()) or .scale(x=so.Temporal()) does not help.

As a bonus, how would I format the x-axis ticks as "Jan 2022", "Feb 2022" etc.?

enter image description here


Solution

  • You can convert your date column as string:

    (so.Plot(df1.assign(date=df1['date'].dt.strftime('%b %Y')), x='date', y='val')
       .add(so.Bar()).show())
    
    # Or, as suggested by @mwaskom:
    so.Plot(x=df1['date'].dt.strftime('%b %Y'), y=df1['val']).add(so.Bar()).show()
    

    Output:

    enter image description here