mrgou
mrgou

Reputation: 2448

Formatting time series axis in Seaborn

I'm learning Seaborn and trying to figure out how I can format an X axis for dates over a yearly period, so that it is readable. Let's assume we have a dataframe which holds weather measurements for each day of an entire year (365 rows).

sns.scatterplot(x = df_weather["DATE"], y = df_weather["MAX_TEMPERATURE_C"], color = 'red')
sns.scatterplot(x = df_weather["DATE"], y = df_weather["MIN_TEMPERATURE_C"], color = 'blue')
plt.show()

enter image description here

How can I ensure that the X axis labels are readable? Ideally, one label per month would be fine.

Thanks!

Upvotes: 1

Views: 2511

Answers (1)

StupidWolf
StupidWolf

Reputation: 46898

Not very sure what your column date is like, but maybe try something like below, first generate some data, I have the date as a string which I guess is something like yours:

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

DATE = pd.date_range('2020-01-01', periods=365, freq='D').strftime('%y%y-%m-%d')
MIN = np.random.uniform(low=10,high=25,size = len(index))
MAX = MIN + np.random.uniform(low=5,high=10,size =len(index))
df = pd.DataFrame({'DATE':DATE,'MIN':MIN,'MAX':MAX})

Plot like you did using sns:

fig, ax = plt.subplots(figsize = (10,4))

ax = sns.scatterplot(x = "DATE", y = "MAX",data=df, color = 'red')
ax = sns.scatterplot(x = "DATE", y = "MIN",data=df, color = 'blue')

Now we define the start of the mths to define ticks:

mths = pd.date_range('2020-01-01', periods=12, freq='MS')

ax.set_xticks(mths.strftime('%y%y-%m-%d'))
ax.set(xticklabels=mths.strftime('%b'))
plt.show()

And it should look ok:

enter image description here

Upvotes: 1

Related Questions