Home > Back-end >  Date Tick-marks (mm/dd) on Slider
Date Tick-marks (mm/dd) on Slider

Time:02-21

I have added a slider to my plot.

ax2 = fig.add_axes([.1, .01, .8, .05])
ax2_Slider = Slider(ax2, 'NormDate', valmin, valmax,  valstep=1, color='w', initcolor='none', track_color='g')
ax2_Slider.valtext.set_visible(False)

In matplotlib, the slider values must be float, not date. Thus I used date2num to convert the dates values.

leftDate = datetime.date.today()  - relativedelta(days=366)
valmin = mpl.dates.date2num(leftDate)
valmax = mpl.dates.date2num(datetime.date.today())

How can I add tick marks to the slider to show mm/dd? Also how to add title showing which date is selected?

CodePudding user response:

Of course, you could set tick labels. But why not also display the actual date?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
from datetime import date, timedelta
from matplotlib.dates import date2num, num2date

#set figure layout
fig = plt.figure(figsize=(10, 5))
gs = fig.add_gridspec(2, 3, width_ratios=[1, 10, 1], height_ratios=[10, 1])

#main panel
ax1 = fig.add_subplot(gs[0, :])
#slider panel
ax2 = fig.add_subplot(gs[1, 1])
valmin = date2num(date.today()  - timedelta(days=366))
valmax = date2num(date.today())
ax2_Slider = Slider(ax2, 'NormDate', valmin, valmax,  valstep=1, color='w', initcolor='none', track_color='g')
#adding and formatting of the date ticks
ax2.add_artist(ax2.xaxis)
x_tick_nums=np.linspace(valmin, valmax, 10)
ax2.set_xticks(x_tick_nums, [num2date(s).strftime("%m-%d") for s in x_tick_nums])

#convert slider value to date
def changed_slider(s):
    ax2_Slider.valtext.set_text(num2date(s).date())
    #...
    #other things that should happen when the slider value changes 

#initiate the correct date display
changed_slider(valmin)
ax2_Slider.on_changed(changed_slider)

plt.show()

Sample output: enter image description here

  • Related