juuubbb
juuubbb

Reputation: 179

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')

Upvotes: 8

Views: 8586

Answers (2)

ignoring_gravity
ignoring_gravity

Reputation: 10486

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

Upvotes: 7

R.V
R.V

Reputation: 100

i think you have 2 options:

  1. convert the time to hour only, for that just extract the hour to new column in your df

df['hour_'] = datetime.hour

than use it as your xaxis

  1. if you need the time in the format you described, it may cause you a visibility problem in which timestamps will overlay each other. i'm using the

plt.xticks(rotation=45, horizontalalignment='right')

ax.xaxis.set_major_locator(plt.MaxNLocator(12))

so first i rotate the text then i'm limiting the ticks number.

here is a full script where i used it:

sns.set()
sns.set_style("whitegrid")
sns.axes_style("whitegrid")

for k, g in df_forPlots.groupby('your_column'):
    fig = plt.figure(figsize=(10,5))
    wide_df = g[['x', 'y', 'z']]
    wide_df.set_index(['x'], inplace=True)
    ax = sns.lineplot(data=wide_df)
    plt.xticks(rotation=45,
                   horizontalalignment='right')
    ax.yaxis.set_major_locator(plt.MaxNLocator(14))
    ax.xaxis.set_major_locator(plt.MaxNLocator(35))
    plt.title(f"your {k} in somthing{g.z.unique()}")
    plt.tight_layout()

hope i halped

Upvotes: -1

Related Questions