简体   繁体   English

交互式 window 中鼠标 position 的不同格式化程序

[英]different formatter for the mouse position in an interactive window

在此处输入图像描述

I have a plot where in abscissa I have the year 2022, and in ordinate a function of time我有一个 plot 横坐标是 2022 年,纵坐标是时间的 function

In [215]: import matplotlib.pyplot as plt
     ...: from matplotlib.dates import MonthLocator, DateFormatter
     ...: from numpy import linspace, sin
     ...: 
     ...: T0 = (2022-1970)*365.25 ; T1 = T0+365 ; T = np.linspace(T0, T1, 366)
     ...: w = 6.28/40
     ...: 
     ...: fig, ax = plt.subplots(figsize=(14,5), constrained_layout=1)
     ...: ax.plot(T,40+15*np.sin(w*T-0.2))
     ...: ax.xaxis.set_major_locator(MonthLocator(bymonth=range(13)))
     ...: ax.xaxis.set_major_formatter(DateFormatter("%b %Y"))
     ...: 
     ...: plt.show()

As you can see from the code, the function is plotted with a one day resolution, but because of my choice for the formatting of x-tick-labels when I move the mouse over the interactive window what I see in the upper right corner is just, eg, "x=May 2022 y=43.31".正如您从代码中看到的那样,function 以一天的分辨率绘制,但是由于我在将鼠标移动到交互式 window 上时选择了 x-tick-labels 的格式,所以我在右上角看到的是只是,例如,“x=2022 年 5 月 y=43.31”。

Is it possible to have a different formatter for the interactive window display of the mouse position?是否可以为鼠标 position 的交互式 window 显示器使用不同的格式化程序?

ax.fmt_xdata controls the formatting of the coordinate in the status bar. ax.fmt_xdata控制状态栏中坐标的格式。 By default, it uses the same format as the x-axis, but you can assign a more specific one.默认情况下,它使用与 x 轴相同的格式,但您可以指定更具体的格式。

Here is an example:这是一个例子:

import matplotlib.pyplot as plt
from matplotlib.dates import MonthLocator, DateFormatter
import numpy as np

T0 = (2022 - 1970) * 365.25
T1 = T0 + 365
T = np.linspace(T0, T1, 366)
w = 6.28 / 40

fig, ax = plt.subplots(figsize=(14, 5), constrained_layout=1)
ax.plot(T, 40 + 15 * np.sin(w * T - 0.2))
ax.xaxis.set_major_locator(MonthLocator(bymonth=range(13)))
ax.xaxis.set_major_formatter(DateFormatter("%b %Y"))
ax.fmt_xdata = DateFormatter("%d %b %Y")
plt.show()

使用 ax.fmt_xdata

You could even go one step further, and override the ax.format_coord function.您甚至可以更进一步地使用 go,并覆盖ax.format_coord function。 This is a function, given an x and y value, to produce the full coordinate string to be displayed in the status bar.这是一个 function,给定一个 x 和 y 值,以生成要在状态栏中显示的完整坐标字符串。 By default, it just combines ax.fmt_xdata and ax.fmt_ydata .默认情况下,它只是结合ax.fmt_xdataax.fmt_ydata

Also the mplcursors library might be of interest. mplcursors库也可能很有趣。 With it, you can obtain the xy coordinates of the nearest point on the curve, and show that information as an annotation, or as overriding the status bar.有了它,您可以获得曲线上最近点的 xy 坐标,并将该信息显示为注释或覆盖状态栏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM