Выбор точек на двух осях в matplotlib - PullRequest
0 голосов
/ 24 января 2020

Я хочу выбрать точки на графике matplotlib в pyplot / tkinter. Тем не менее, я использую графики с двумя осями Y и с помощью ax.twinx () я видел другой ответ переполнения стека, что использование ax.twinx () предотвращает выбор первой оси. Я видел это из первых рук в моем тестировании. Есть ли способ обойти эту проблему без использования ax.twinx ()?

Другими словами, есть ли способ создания нескольких осей на одном графике, правильно масштабированный без использования ax.twinx ()?

Вот мой пример кода. При этом я могу выбрать и выделить точки на ax2, что является синусоидальным графиком. Я не могу выбрать из топора 1.

Я должен также отметить, что я ограничен Python 2.7 и использую matplotlib 1.3.1.

import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
from matplotlib import pyplot as plt

import Tkinter as tk
import ttk
from scipy import spatial
import numpy as np


LARGE_FONT= ("Verdana", 12)

def createPlot():
  f = Figure(figsize=(5,5), dpi=100)
  ax1 = f.add_subplot(111)
  #f, ax1 = plt.subplots()
  ax1.plot([1,2,3,4,5,6,7,8],[5,6,1,3,8,9,3,5], picker=2, markevery=3)
  ax1.set_picker(True)
  np.arange(0.01, 8.0, 0.01)
  t = np.arange(0.01, 10.0, 0.01)
  data2 = np.sin(2 * np.pi * t)
  ax2 = ax1.twinx()
  ax2.plot(t, data2, color='r', picker=2)
  ax2.tick_params(axis='y', labelcolor='r')

  return f


class PlotsNotebook(tk.Frame):

  def __init__(self, isapp=True, name="plotnotebook"):
    tk.Frame.__init__(self, name=name)
    self.pack(expand=True, fill="both")
    self.master.title("Plot Demo")
    self.isapp = isapp
    self._createNotebook()
    self.addFigure(createPlot(), "My Plot")
    self.addFigure(createPlot(), "My Other Plot")

  def _createNotebook(self):
    demo_panel = tk.Frame(self, name="demo")
    demo_panel.pack(side="top", fill="both", expand=True)
    self.xy_label = tk.Label(demo_panel, text="x = 0      y=0")
    self.xy_label.pack(side="bottom")
    self.notebook = ttk.Notebook(demo_panel, name="notebook")
    self.notebook.enable_traversal()
    self.notebook.pack(fill="both", expand=True)
    #self.addTab(TestPlot(self.master, self.notebook))


  def addFigure(self,fig , text="test"):
    frame = tk.Frame(self.notebook)
    canvas = FigureCanvasTkAgg(fig, master=frame)
    fig.canvas.mpl_connect("pick_event", self.onClick)
    canvas.show()
    canvas.get_tk_widget().pack(side="top", fill="both", expand=True)
    self.notebook.add(frame, text=text)

  def onClick(self, event):
    print "Artist is ", event.artist
    print "Type is ", type(event.artist)
    if isinstance(event.artist, matplotlib.lines.Line2D):
      thisline = event.artist
      xdata = thisline.get_xdata()
      ydata = thisline.get_ydata()
      event = event.mouseevent
      xpt, ypt = event.inaxes.transData.inverted().transform((event.x, event.y))
      arr = np.array(zip(xdata, ydata))
      nearest = spatial.KDTree(arr).query([xpt,ypt])
      nearest_idx = nearest[1]
      nearest_pt = arr[nearest_idx]
      self.xy_label.config(text="x=%f      y=%f" % (nearest_pt[0], nearest_pt[1]))
      ax = thisline.axes
      #thisline.set_xdata(xdata)
      #thisline.set_ydata(ydata)
      thisline.set_markevery([nearest_idx,len(xdata)+1])
      thisline.set_marker("o")
      #ax.plot(xdata,ydata, markevery=(nearest_idx, 1))
      #thisline.set_markevery((nearest_idx,1))
      #ax.relim()
      #ax.autoscale_view()
      ax.figure.canvas.draw()
      ax.figure.canvas.flush_events()
      #plt.show()

      print "nearest_idx is ", nearest_idx
      print "nearest_pt is ", nearest_pt




#root = tk.Tk()
app = PlotsNotebook()
app.mainloop()
...