Chendo
Chendo

Reputation: 45

Seaborn lineplot showing year 1970 on x-axis

I want to create a Seaborn lineplot with below (shortened) dataframe as underlying data (Date on x axis and A and B on y axis)

Date A B
2024-08-01 48.06 30.9
2024-08-02 49.06 31.9
2024-08-05 50.06 32.9

When I create the lineplot I am getting wrong days though on the x axis (starting from 1970-01-01 and ending at 1970-01-03.

What magic trick is needed here to show the correct dates?

Many thanks as always

plot = sns.lineplot(data = df)

format_ymd = mdates.DateFormatter('%Y-%m-%d')
plot.xaxis.set_major_formatter(format_ymd)

plt.xticks(rotation=45)

Upvotes: 0

Views: 62

Answers (1)

D.lola
D.lola

Reputation: 2294

Have you checked the 'Date' column you are interested in is in fact a date object? By default, Seaborn and Matplotlib may not interpret the 'Date' column correctly. However you can check this.

I have made some changes this should be fine.

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

# Sample data
data = {
    'Date': ['2024-08-01', '2024-08-02', '2024-08-05'],
    'A': [48.06, 49.06, 50.06],
    'B': [30.9, 31.9, 32.9]
}

# Create DataFrame
df = pd.DataFrame(data)

# Convert 'Date' to datetime
df['Date'] = pd.to_datetime(df['Date'])

# Plot with Seaborn
plt.figure(figsize=(10, 6))
plot = sns.lineplot(x='Date', y='A', data=df, label='A')
sns.lineplot(x='Date', y='B', data=df, label='B')

# Format the x-axis to show dates correctly
format_ymd = mdates.DateFormatter('%Y-%m-%d')
plot.xaxis.set_major_formatter(format_ymd)

# Rotate x-axis labels for better readability
plt.xticks(rotation=45)

plt.legend()
plt.show()

Upvotes: 0

Related Questions