matplotlib 的光标信息似乎依赖于 Tick 分辨率 - 我该如何改变这种依赖关系 [英] matplotlib's cursor info seems to be dependant from Tick resolution - how can I change this dependancy

查看:51
本文介绍了matplotlib 的光标信息似乎依赖于 Tick 分辨率 - 我该如何改变这种依赖关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用matplotlib,如何在交互式绘图的右下角看到日期值的光标的确切值?

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:

以下代码示例具有不同的刻度分辨率.因此,在屏幕快照的右下角,光标值一次是 2020 ,一次是 2020-09 .

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.

我希望将其设为 2020-09-01 - 以便数据具有这种分辨率/粒度.

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()

推荐答案

要将日期时间轴的x坐标设置为与轴上使用的实际格式不同的格式,可以设置 Axes.fmt_xdata 属性给可调用的可调用对象,该可调用对象将位置放在其中并输出所需的字符串.在这种情况下,

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")

示例:

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()

这篇关于matplotlib 的光标信息似乎依赖于 Tick 分辨率 - 我该如何改变这种依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆