Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to plot int to datetime on X-axis using Seaborn?
When working with Seaborn plots, you may need to display integer timestamps as readable datetime labels on the X-axis. This is commonly required when dealing with Unix timestamps or other integer-based date representations.
Understanding the Problem
Integer timestamps (like Unix timestamps) are not human-readable. Converting them to datetime format on the X-axis makes your plots more interpretable and professional-looking.
Complete Example
Here's how to convert integer timestamps to datetime labels on the X-axis ?
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# Set the figure size
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True
# Create DataFrame with integer timestamps
df = pd.DataFrame([
[23, 'James', 1259969793926],
[39, 'Jimmy', 1259969793927],
[56, 'Jack', 1259969793929],
[60, 'Tom', 1259969793928],
[80, 'Tim', 1259969793939]
], columns=['marks', 'names', 'dob'])
print("Original DataFrame:")
print(df)
print("\nData types:")
print(df.dtypes)
# Create countplot with integer timestamps
ax = sns.countplot(x="dob", data=df)
# Convert integer timestamps to datetime labels
ax.set_xticklabels([
pd.to_datetime(tm, unit='ms').strftime('%Y-%m-%d %H:%M:%S')
for tm in ax.get_xticks()
], rotation=45)
# Add labels and title
ax.set_xlabel('Date of Birth')
ax.set_ylabel('Count')
ax.set_title('Count Plot with DateTime X-axis Labels')
plt.tight_layout()
plt.show()
Original DataFrame: marks names dob 0 23 James 1259969793926 1 39 Jimmy 1259969793927 2 56 Jack 1259969793929 3 60 Tom 1259969793928 4 80 Tim 1259969793939 Data types: marks int64 names object dob int64 dtype: object
How It Works
The key steps in this process are ?
ax.get_xticks() − Retrieves the current X-axis tick positions (integer values)
pd.to_datetime(tm, unit='ms') − Converts each integer timestamp to datetime object
strftime('%Y-%m-%d %H:%M:%S') − Formats datetime as readable string
ax.set_xticklabels() − Replaces integer labels with formatted datetime strings
Alternative Approach with Line Plot
For time series data, you might prefer a line plot ?
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# Create sample time series data
data = pd.DataFrame({
'timestamp': [1609459200, 1609545600, 1609632000, 1609718400, 1609804800],
'value': [10, 25, 30, 15, 35]
})
# Convert timestamp to datetime for plotting
data['datetime'] = pd.to_datetime(data['timestamp'], unit='s')
plt.figure(figsize=(10, 6))
sns.lineplot(x='datetime', y='value', data=data, marker='o')
plt.xticks(rotation=45)
plt.title('Time Series Plot with DateTime X-axis')
plt.tight_layout()
plt.show()
print("Converted DataFrame:")
print(data)
Converted DataFrame: timestamp value datetime 0 1609459200 10 2021-01-01 1 1609545600 25 2021-01-02 2 1609632000 30 2021-01-03 3 1609718400 15 2021-01-04 4 1609804800 35 2021-01-05
Key Parameters
| Parameter | Description | Common Values |
|---|---|---|
unit |
Time unit for conversion | 's', 'ms', 'us', 'ns' |
rotation |
Label rotation angle | 0, 45, 90 |
strftime |
Date format string | '%Y-%m-%d', '%Y-%m-%d %H:%M:%S' |
Conclusion
Converting integer timestamps to datetime labels improves plot readability. Use pd.to_datetime() with appropriate units and set_xticklabels() to format the X-axis properly. Consider using rotation for better label visibility.
