Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying x ticks labels in seaborn

I am trying to modify the format of the x-tick label to date format (%m-%d).

My data consists of hourly data values over a certain period of dates. I am trying to plot the data for 14 days. However when I run I get x labels fully jumbled up.

enter image description here

Is there any way I can show only dates and skip hourly values on the x-axis. ? Is there any way to modify x ticks where I can skip labels for hours and show labels only for dates? I am using seaborn.

After suggestion from comment by i edited my code to plot as below:

fig, ax = plt.pyplot.subplots()
g = sns.barplot(data=data_n,x='datetime',y='hourly_return')
g.xaxis.set_major_formatter(plt.dates.DateFormatter("%d-%b"))

But I got the following error:

ValueError: DateFormatter found a value of x=0, which is an illegal 
date; this usually occurs because you have not informed the axis that 
it is plotting dates, e.g., with ax.xaxis_date()

Upon checking the datetime column I get following output with data type type of the column:

0     2020-01-01 00:00:00
1     2020-01-01 01:00:00
2     2020-01-01 02:00:00
3     2020-01-01 03:00:00
4     2020-01-01 04:00:00
          ...        
307   2020-01-13 19:00:00
308   2020-01-13 20:00:00
309   2020-01-13 21:00:00
310   2020-01-13 22:00:00
311   2020-01-13 23:00:00
Name: datetime, Length: 312, dtype: datetime64[ns]

I was suspecting the x ticks so when I ran g.get_xticks() [which gets the ticks on x-axis], I got output as ordinal numbers. Can anyone tell why is this happening?

like image 308
Naveen Gabriel Avatar asked Jun 19 '20 15:06

Naveen Gabriel


1 Answers

1. Approach for Drawing Line Plot with x-axis datetime

Can you try changing x axis format as below

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

## create dummy dataframe
datelist = pd.date_range(start='2020-01-01 00:00:00', periods=312,freq='1H').tolist()
#create dummy dataframe
df = pd.DataFrame(datelist, columns=["datetime"])
df["val"] = [i for i in range(1,312+1)]
df.head()

Below is the dataframe info

enter image description here

Draw plot

fig, ax = plt.subplots()
chart = sns.lineplot(data=df, ax=ax, x="datetime",y="val")
ax.xaxis.set_major_formatter(dates.DateFormatter("%d-%b"))

Output:

enter image description here

2. Approach for Drawing Bar plot using seaborn with x-axis datetime

There is a problem with the above approach if you draw for barplot. So, will use below code

fig, ax = plt.subplots()
## barplot
chart = sns.barplot(data=df, ax=ax,x="datetime",y="val")

## freq of showing dates, since frequency of datetime in our data is 1H. 
## so, will have every day 24data points
## Trying to calculate the frequency by each day 
## (assumed points are collected every hours in each day, 24)
## set the frequency for labelling the xaxis
freq = int(24)
# set the xlabels as the datetime data for the given labelling frequency,
# also use only the date for the label
ax.set_xticklabels(df.iloc[::freq]["datetime"].dt.strftime("%d-%b-%y"))
# set the xticks at the same frequency as the xlabels
xtix = ax.get_xticks()
ax.set_xticks(xtix[::freq])
# nicer label format for dates
fig.autofmt_xdate()

plt.show()

output:

enter image description here

like image 193
Narendra Prasath Avatar answered Sep 22 '22 00:09

Narendra Prasath