Я прочитал в " Значение курсора Matplotlib с двумя осями ", как обновить область строки состояния диаграммы Matplotlib со значениями под курсором при перемещении курсора.Я использовал этот пример для создания следующего кода, который обновляет область строки состояния следующими значениями под курсором-перекрестием: значение оси x (x), два значения ряда в кадре данных (s1 и s2)и два значения по оси Y, где их касается горизонтальная линия курсора («левый у» и «правый у»).
У меня два вопроса:
1) Есть ли способ отобразить значение оси x (x) и значения обеих серий в легенде (s1 и s2), чтобы легендаобновляется с этими значениями при перемещении курсора-перекрестия?
2) Есть ли способ отобразить значения оси Y, когда горизонтальная линия курсора касается / пересекает две оси Y ('слева)y 'и' right 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)
