Search code examples
pythonmatplotlibseaborndatetime-formatxticks

Setting xticks to the first day of the month


I´m practicing seaborn visualization with a database created from scratch. The point is that I want to see the data from this stock market prices visualizing only the first day of the month but the steps that it has are irregular: How can I indicate it to .xticks()? I leave you what I´ve done:

Sample Data

import pandas as pd
import numpy as np
import random
from datetime import datetime, timedelta

# Create a sample dataset
np.random.seed(42)
num_entries = 100

start_date = datetime(2023, 1, 1)
date_list = [start_date + timedelta(days=i) for i in range(num_entries)]
prices = np.random.uniform(50, 200, num_entries)
volumes = np.random.randint(1000, 10000, num_entries)
returns = np.random.uniform(-0.1, 0.1, num_entries)

data = {
    "Date": date_list,
    "Price": prices,
    "Volume": volumes,
    "Returns": returns
}

df = pd.DataFrame(data)

Plotting

sns.lineplot( x = "Date", y = "Price", data = df)
plt.title("Evolution of prices along time")
plt.xlabel("Date")
plt.xticks(ticks =np.arange(0,101,step=31))
plt.ylabel("Price")
plt.show()

enter image description here


Solution

  • matplotlib.dates has mdates module to achieve this. First, you need to define the xticks with a month frequency. After that, you can edit the xticklabels to also show the day of each date. Example code:

    import seaborn as sns
    import matplotlib.dates as mdates
    
    ax = sns.lineplot(x="Date", y="Price", data=df)
    ax.xaxis.set_major_locator(mdates.MonthLocator())
    

    enter image description here