Seaborn after dates.num2date(x) not showing X equals (x=y=7.51) on the graph, lmplot

112 Views Asked by At

After converting dates to floats (necessary to use dates in lmplot) then, when trying to set ax.set_xticklabels the X disappears on the graph in the lower right corner, eg. (x=y=7.51).enter image description here

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import dates
import seaborn as sns


df1 = pd.DataFrame({'X': ['2020-01-01', '2020-01-03',  '2020-01-03', '2020-01-09'],
                    'Y': [5, 8, 1, 9]})
df2 = pd.DataFrame({'X': pd.date_range('2020.01.01', '2020.01.10').astype(str),
                    'Y': 0})
df3 = pd.merge(df2, df1, how='left', on=['X'])
df3 = df3[['X', 'Y_y']]

x = dates.datestr2num(df3.X)

new_arr = df3['Y_y'].to_numpy()

df4 = pd.DataFrame({'X': x,
                    'Y': new_arr})

ax = sns.lmplot(x='X', y='Y', data=df4)

uniqe_time2num = df4['X'].unique()

date = [date.strftime('%Y-%m-%d') for date in dates.num2date(uniqe_time2num)]

ax.set(xticks=uniqe_time2num, yticks=range(len(df4.Y)))
ax.set_xticklabels(date, rotation=45)  # <-- here

1

There are 1 best solutions below

2
On

This could fix it, need to add ax.tight_layout() at the end:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import dates
import seaborn as sns


df1 = pd.DataFrame({'X': ['2020-01-01', '2020-01-03',  '2020-01-03', '2020-01-09'],
                'Y': [5, 8, 1, 9]})
df2 = pd.DataFrame({'X': pd.date_range('2020.01.01', '2020.01.10').astype(str),
                'Y': 0})
df3 = pd.merge(df2, df1, how='left', on=['X'])
df3 = df3[['X', 'Y_y']]

x = dates.datestr2num(df3.X)

new_arr = df3['Y_y'].to_numpy()

df4 = pd.DataFrame({'X': x,
                'Y': new_arr})

ax = sns.lmplot(x='X', y='Y', data=df4)

uniqe_time2num = df4['X'].unique()

date = [date.strftime('%Y-%m-%d') for date in dates.num2date(uniqe_time2num)]

ax.set(xticks=pd.to_numeric(uniqe_time2num), yticks=range(len(df4.Y)))
ax.set_xticklabels(date, rotation=45)  # <-- here
ax.tight_layout() # <- fix here, makes sure everything looks fine in the fig

Note that ax.tight_layout() does work as this is the output I get. The X is fully visible:

ax layout output

A second option, is to save with bbox_inches:

ax = sns.lmplot(x='X', y='Y', data=df4)

uniqe_time2num = df4['X'].unique()

date = [date.strftime('%Y-%m-%d') for date in dates.num2date(uniqe_time2num)]

ax.set(xticks=pd.to_numeric(uniqe_time2num), yticks=range(len(df4.Y)))
ax.set_xticklabels(date, rotation=45)
plt.savefig('axfig.png',dpi=300, bbox_inches = "tight")