Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use time as x axis for a scatterplot with seaborn?

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(my_df.index, my_df['values'])
fig.set(xlabel='time', ylabel='values')
like image 866
juuubbb Avatar asked Dec 18 '19 10:12

juuubbb


1 Answers

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(df.index, 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

like image 61
ignoring_gravity Avatar answered Oct 22 '22 00:10

ignoring_gravity