how to show two x axis ticks , one with weeks, and the second with months in python

You can achieve this by creating a twin x-axis in matplotlib and then formatting the ticks on each axis accordingly. Here's an example of how you can do it:

main.py
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# Generate example data
dates = pd.date_range(start='2022-01-01', end='2022-03-31', freq='D')
values = np.random.rand(len(dates))

# Create a figure and axes
fig, ax1 = plt.subplots()

# Plot the data
ax1.plot(dates, values)

# Create a twin x-axis
ax2 = ax1.twiny()

# Set the limits and ticks for each axis
ax1.set_xlim(dates[0], dates[-1])
ax1.xaxis.set_major_locator(plt.MaxNLocator(10)) # Set the number of major ticks for the first axis

ax2.set_xlim(ax1.get_xlim()) # Set the same limits for the second axis
ax2.xaxis.set_major_locator(plt.MaxNLocator(3)) # Set the number of major ticks for the second axis

# Format the major ticks on each axis
ax1.xaxis.set_major_formatter(plt.FuncFormatter(lambda x, pos: dates[int(x)].strftime('%b %d'))) # Format the ticks on the first axis as month and day
ax2.xaxis.set_major_formatter(plt.FuncFormatter(lambda x, pos: dates[int(x)].strftime('%b'))) # Format the ticks on the second axis as month

# Rotate the labels on the second axis
for tick in ax2.get_xticklabels():
    tick.set_rotation(45)

plt.show()
1131 chars
34 lines

In this example, we use the twiny() function to create a second x-axis that shares the same y-axis with the first axis (ax1). We then set the limits and ticks for each axis separately using the set_xlim() and xaxis.set_major_locator() functions. Finally, we format the major ticks on each axis using the xaxis.set_major_formatter() function and rotate the labels on the second axis using a loop.

Note that this example uses pandas to generate example data, but you can replace it with your own data as needed.

related categories

gistlibby LogSnag