Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
Add Comment
Please, Sign In to add comment