【问题标题】:Seaborn after dates.num2date(x) not showing X equals (x=y=7.51) on the graph, lmplot在 dates.num2date(x) 之后的 Seaborn 未在图表 lmplot 上显示 X 等于 (x=y=7.51)
【发布时间】:2022-01-22 03:57:45
【问题描述】:

在将日期转换为浮点数之后(在 lmplot 中必须使用日期),然后在尝试设置 ax.set_xticklabels X 在右下角的图表上消失,例如。 (x=y=7.51).

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

【问题讨论】:

    标签: python pandas matplotlib seaborn lmplot


    【解决方案1】:

    这样可以解决,需要在末尾添加ax.tight_layout()

    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() # <-0 fix here, makes sure everything looks fine in the fig
    

    【讨论】:

    • 谢谢,但不幸的是添加“ax.tight_layout()”并不能解决这个问题...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多