2

With matplotlib, how can I see the exact value of the cursor for date values at the bottom right of the interactive plot?

It seems, that this is dependent from the tick resolution:

the following code example has different tick resolution. As an effect, at the bottom right of the screenshots one time the cursor value is 2020, one time it is 2020-09.

I would like to have it as 2020-09-01 - so that it is with this resolution / granularity that the data has.

import datetime
import pandas as pd
import matplotlib
min_date = datetime.datetime.now().date()
max_date = min_date + datetime.timedelta(days=2*365)
date_range = [min_date + datetime.timedelta(days=x)
              for x in range(0, (max_date - min_date).days)]
df = pd.DataFrame(date_range)
yRange = range(df.shape[0])
df["y"] = yRange
df.columns = ["x","y"]
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
plt.plot(df["x"], df["y"], "-o", markersize=2)
plt.show()

axes = plt.gca()
import matplotlib.ticker as ticker
tick_spacing = 50
axes.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
plt.rcParams["figure.dpi"] = 200
plt.xticks(rotation=20)
plt.grid()
plt.plot(df["x"], df["y"], "-o", markersize=2)
plt.show()

monthly resolution

yearly resolution

user7468395
  • 1,299
  • 2
  • 10
  • 23

1 Answers1

3

In order to format the x coordinate for datetime axes differently than the actual format used on the axes, you can set the Axes.fmt_xdata attribute to a callable that takes the position in and outputs the desired string. In this case,

ax.fmt_xdata = lambda x: matplotlib.dates.num2date(x).strftime("%Y-%m-%d")

Example:

from datetime import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

plt.plot([datetime.now(), datetime(2020,6,6)], [1,2], "-o")
plt.gca().fmt_xdata = lambda x: mdates.num2date(x).strftime("%Y-%m-%d")
plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712