我已阅读“ Matplotlib cursor value with two axes”中如何在游标四处移动时使用游标下的值更新matplotlib图表的状态栏区域。我已经使用此示例创建了以下代码,该代码使用十字光标下的以下值更新状态栏区域: x轴值(x), 数据帧中序列的两个值(s1和s2),以及 光标的水平线触碰到的两个y轴值(“左y”和“右y”)。
我有两个问题:
1)是否可以在图例中显示x轴值(x)和两个系列的值(s1和s2),以便在十字形光标移动时,图例以这些值更新? / p>
2)有没有一种方法可以显示y轴值,其中光标的水平线触摸/越过y轴外侧的两个y轴(“左y”和“右y”)并随着十字光标移动来更新它们?
from random import randrange
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.widgets import Cursor
# https://stackoverflow.com/questions/21583965/matplotlib-cursor-value-with-two-axes
def make_format(current, other, data):
# current and other are axes
def format_coord(x, y):
# x, y are data coordinates
# convert to display coords
display_coord = current.transData.transform((x,y))
inv = other.transData.inverted()
# convert back to data coords with respect to ax
other_ax_data_coord = inv.transform(display_coord)
return 'x: {:.1f}'.format(int(round(x))) + ', left y: {:.1f}'.format(other_ax_data_coord[1]) + ', s1: {:.1f}'.format(data.iloc[int(round(x)), 0]) + ', s2: {:.1f}'.format(data.iloc[int(round(x)), 1]) + ', right y: {:.1f}'.format(y)
return format_coord
data = pd.DataFrame(dict(
s1=[randrange(-1000, 1000) for _ in range(100)],
s2=[randrange(-100, 100) for _ in range(100)],
)).cumsum()
cols = data.columns
fig, ax_host = plt.subplots()
# Get default color style from pandas
colors = getattr(getattr(pd.plotting, '_style'), '_get_standard_colors')(num_colors=len(cols))
# First axis
ax_host = data.loc[:, cols[0]].plot( ax=ax_host, label=cols[0], color=colors[0])
ax_host.set_ylabel(ylabel=cols[0])
legend_handle_host, label_host = ax_host.get_legend_handles_labels()
# Second y-axis
ax_twinx = ax_host.twinx()
ax_twinx.spines['right'].set_position(('axes', 1))
line = data.loc[:, cols[1]].plot(ax=ax_twinx, label=cols[1], color=colors[1])
ax_twinx.set_ylabel(ylabel=cols[1])
# Proper legend position
legend_handle_twinx, label_twinx = ax_twinx.get_legend_handles_labels()
ax_host.legend(legend_handle_host+legend_handle_twinx, label_host+label_twinx, loc=0)
crosshair = Cursor(ax_twinx, useblit=True, color='black', linewidth=1)
ax_twinx.format_coord = make_format(ax_twinx, ax_host, data)
plt.show(block=True)