Guest User

Untitled

a guest
Oct 17th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. from random import randrange
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. from matplotlib.widgets import Cursor
  5.  
  6. # https://stackoverflow.com/questions/21583965/matplotlib-cursor-value-with-two-axes
  7. def make_format(current, other, data):
  8. # current and other are axes
  9. def format_coord(x, y):
  10. # x, y are data coordinates
  11. # convert to display coords
  12. display_coord = current.transData.transform((x,y))
  13. inv = other.transData.inverted()
  14. # convert back to data coords with respect to ax
  15. other_ax_data_coord = inv.transform(display_coord)
  16. 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)
  17.  
  18. return format_coord
  19.  
  20. data = pd.DataFrame(dict(
  21. s1=[randrange(-1000, 1000) for _ in range(100)],
  22. s2=[randrange(-100, 100) for _ in range(100)],
  23. )).cumsum()
  24. cols = data.columns
  25.  
  26. fig, ax_host = plt.subplots()
  27.  
  28. # Get default color style from pandas
  29. colors = getattr(getattr(pd.plotting, '_style'), '_get_standard_colors')(num_colors=len(cols))
  30.  
  31. # First axis
  32. ax_host = data.loc[:, cols[0]].plot( ax=ax_host, label=cols[0], color=colors[0])
  33. ax_host.set_ylabel(ylabel=cols[0])
  34. legend_handle_host, label_host = ax_host.get_legend_handles_labels()
  35.  
  36. # Second y-axis
  37. ax_twinx = ax_host.twinx()
  38. ax_twinx.spines['right'].set_position(('axes', 1))
  39. line = data.loc[:, cols[1]].plot(ax=ax_twinx, label=cols[1], color=colors[1])
  40. ax_twinx.set_ylabel(ylabel=cols[1])
  41.  
  42. # Proper legend position
  43. legend_handle_twinx, label_twinx = ax_twinx.get_legend_handles_labels()
  44. ax_host.legend(legend_handle_host+legend_handle_twinx, label_host+label_twinx, loc=0)
  45.  
  46. crosshair = Cursor(ax_twinx, useblit=True, color='black', linewidth=1)
  47.  
  48. ax_twinx.format_coord = make_format(ax_twinx, ax_host, data)
  49.  
  50. plt.show(block=True)
Add Comment
Please, Sign In to add comment