add a secondary xaxis that shows minutes instead of seconds in matplotlib in python

To add a secondary x-axis that shows minutes instead of seconds in matplotlib, you can use the twinx function to create a secondary y-axis and then set the ticks and labels of the secondary x-axis to display minutes instead of seconds. Here's an example:

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

# Generate some data
x = np.linspace(0, 10, 1000)
y = np.sin(x)

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

# Plot the data on the primary x-axis
ax1.plot(x, y, color='b')
ax1.set_xlabel('Time (seconds)')
ax1.set_ylabel('Data 1')

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

# Set the ticks and labels of the secondary x-axis
x_ticks = np.arange(0, 11, 2) * 60  # Convert seconds to minutes
x_labels = [f"{int(t/60):02d}:{int(t%60):02d}" for t in x_ticks]  # Format as minutes:seconds
ax2.set_xlim(ax1.get_xlim())
ax2.set_xticks(x_ticks)
ax2.set_xticklabels(x_labels)
ax2.set_xlabel('Time (minutes)')

plt.show()
681 chars
28 lines

In this example, the primary x-axis shows the time in seconds, and the secondary x-axis shows the time in minutes. The ax1.twiny() function creates a secondary x-axis that shares the same y-axis as the primary x-axis (ax1). The tick values and labels for the secondary x-axis are set using the set_xticks and set_xticklabels methods. The tick values are converted from seconds to minutes using numpy operations, and the tick labels are formatted as minutes:seconds using a list comprehension.

Hope this helps!

related categories

gistlibby LogSnag