Title: Modifying x ticks labels in seaborn
Tags: python;data-visualization;seaborn
Question: 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.
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(&quot;%d-%b&quot;))
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?


Here is another answer: 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=[&quot;datetime&quot;])
df[&quot;val&quot;] = [i for i in range(1,312+1)]
df.head()
Below is the dataframe info
Draw plot
fig, ax = plt.subplots()
chart = sns.lineplot(data=df, ax=ax, x=&quot;datetime&quot;,y=&quot;val&quot;)
ax.xaxis.set_major_formatter(dates.DateFormatter(&quot;%d-%b&quot;))
Output:
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=&quot;datetime&quot;,y=&quot;val&quot;)
## 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[75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0req][&quot;datetime&quot;].dt.strftime(&quot;%d-%b-%y&quot;))
# set the xticks at the same frequency as the xlabels
xtix = ax.get_xticks()
ax.set_xticks(xtix[75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0req])
# nicer label format for dates
fig.autofmt_xdate()
plt.show()
output:
Comment for this answer: I am getting below erro when i execute that: '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()'
Comment for this answer: My data-frame column is definitely of type date-time object.
Comment for this answer: It still converts the x axis values to ordinal values. However, sns. lineplot gives correct output. Using sns.barplot gives an issue..
Comment for this answer: thanks it solved my problem a bit but not entirely..
Comment for this answer: means that x values are not in `datetime` object. you convert your x column to datetime object as `pd.to_datetime(df["xaxis"])`
Comment for this answer: @NaveenGabriel if you are not passing your x axis implicitly then you could change your dataframe index value as `datetime object`.
Comment for this answer: Can you provide your X axis values here?
Comment for this answer: Error says, x axis not set properly. By default x axis takes as `index` value in the dataframe. Can you try change your index value as datetime column values. you can  change index value like `df.index = df.datetime`
Comment for this answer: @NaveenGabriel Yes, Even I faced the same issue. Hence I have updated the solution for barplot as well. Check the updated solution. Upvote if it worked for you. Thanks
Comment for this answer: @NaveenGabriel, Hope the updated solution works for you.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2020:00:06/19/20', 'FavoriteCount': 3.0, 'PostTypeId': 1, 'Tags': '<python><data-visualization><seaborn>', 'Title': 'Modifying x ticks labels in seaborn', 'ViewCount': 10483, 'id': 62473172, 'user_AboutMe': None, 'user_AccountId': 2487661.0, 'user_DisplayName': 'Naveen Gabriel', 'user_Reputation': 669.0, 'user_Views': 165.0, 'user_id': 2165803.0}}