Python matplotlib doesn't show full date on mouse hover

别来无恙 提交于 2021-01-27 17:10:00

问题


I have a dataframe with date index and temperature values:

Date     Temperature
2015-10-21     9.118
2015-10-22     9.099
2015-10-23     8.945
2015-10-26     8.848
2015-10-27     8.848
2015-10-28     8.829
2015-10-30     8.935
2015-11-02     9.302
2015-11-03     9.012
2015-11-04     9.109
...
2017-10-16    10.160
2017-10-17    10.180
2017-10-18    10.140
2017-10-19    10.370
2017-10-20    10.360

Plotting it using interactive %matplotlib notebook shows the temperature, year/month on the bottom right, but omits the day.

#%matplotlib notebook
import pandas as pd
import matplotlib.pyplot as plt

x_axis = df.index.tolist()
y_axis = df['temperature'].tolist()

plt.plot(x_axis, y_axis)
plt.show()

How can I get it to show the day? Any format is fine, but preferably '01-Jan-2017'.


回答1:


You can use format_coord method of the axes to specify the format of the text shown in the status bar or lower left corner of the notebook figure.

In case this is to be a datetime object, the use of a matplotlib.dates.DateFormatter is reasonable. The format specifier would then be "%d-%b-%Y" for something like '01-Jan-2017'.

import matplotlib.dates
datefmt = matplotlib.dates.DateFormatter("%d-%b-%Y")
fmt = lambda x,y : "{}, {:.5g}".format(datefmt(x), y)
plt.gca().format_coord = fmt



来源:https://stackoverflow.com/questions/46853259/python-matplotlib-doesnt-show-full-date-on-mouse-hover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!