Search code examples
pythonpandasseabornscatter-plot

How to use time as x axis for seaborn.scatterplot


I have a simple dataframe with the time as index and dummy values as example.

my sample

I did a simple scatter plot as you see here:

enter image description here

Simple question: How to adjust the xaxis, so that all time values from 00:00 to 23:00 are visible in the xaxis? The rest of the plot is fine, it shows all the datapoints, it is just the labeling. Tried different things but didn't work out.

All my code so far is:

import pandas as pd
import seaborn as sns
import matplotlib.dates as mdates
from datetime import time

data = []
for i in range(0, 24):
    temp_list = []
    temp_list.append(time(i))
    temp_list.append(i)
    data.append(temp_list)

my_df = pd.DataFrame(data, columns=["time", "values"])    
my_df.set_index(['time'],inplace=True)
my_df
fig = sns.scatterplot(x=my_df.index, y=my_df['values'])
fig.set(xlabel='time', ylabel='values')

Solution

  • I think you're gonna have to go down to the matplotlib level for this:

    import pandas as pd
    import seaborn as sns
    import matplotlib.dates as mdates
    from datetime import time
    import matplotlib.pyplot as plt
    
    data = []
    for i in range(0, 24):
        temp_list = []
        temp_list.append(time(i))
        temp_list.append(i)
        data.append(temp_list)
    
    df = pd.DataFrame(data, columns=["time", "values"])  
    df.time = pd.to_datetime(df.time, format='%H:%M:%S')
    df.set_index(['time'],inplace=True)
    ax = sns.scatterplot(x=df.index, y=df["values"])
    ax.set(xlabel="time", ylabel="measured values")
    ax.set_xlim(df.index[0], df.index[-1])
    ax.xaxis.set_major_locator(mdates.HourLocator())
    ax.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S"))
    ax.tick_params(axis="x", rotation=45)
    

    This produces

    enter image description here