import sys
import numpy as np
from PyQt4.QtCore import *
from PyQt4.QtGui import *
#from xlwt import *
#from pylab import plot, show
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar2
class ViewWidget(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
# create a simple main widget to keep the figure
self.mainWidget = QWidget()
self.setCentralWidget(self.mainWidget)
layout = QVBoxLayout()
self.mainWidget.setLayout(layout)
# create a figure
self.figure_canvas = FigureCanvas(Figure())
layout.addWidget(self.figure_canvas, 10)
# and the axes for the figure
self.axes = self.figure_canvas.figure.add_subplot(111)
# Bind the 'pick' event for clicking on one of the curves
cid = self.figure_canvas.mpl_connect('pick_event',self.onpick)
x = np.linspace(0.,2*np.pi,100)
self.axes.plot(x,np.sin(x),label='sin(x) ',picker=5)
self.axes.plot(x,np.cos(x),label='cos(x) ',picker=5)
self.axes.figure.set_facecolor('white')
self.axes.grid('on')
self.axes.legend()
self.figure_canvas.draw()
# add a navigation toolbar
self.navigation_toolbar = NavigationToolbar2(self.figure_canvas, self)
layout.addWidget(self.navigation_toolbar, 0)
self.print_button = QPushButton()
self.print_button.setIcon(QIcon("Fileprint.png"))
self.print_button.setToolTip("Print the figure")
self.navigation_toolbar.addWidget(self.print_button)
self.connect(self.print_button, SIGNAL('clicked()'), self.goPrinter)
self.quit_button = QPushButton("&Quit")
self.navigation_toolbar.addWidget(self.quit_button)
self.connect(self.quit_button, SIGNAL('clicked()'), self.close)
def onpick(self, event):
thisline = event.artist
xdata = thisline.get_xdata()
ydata = thisline.get_ydata()
ind = event.ind
print str(xdata[ind][0])
print ind[0], ydata[ind][0]
print xdata[ind][0], ydata[ind][0]
#
# The annotation doesn't work. For what reason ?
#
self.axes.annotate(str(xdata[ind][0]), xy=(ind[0], ydata[ind][0]), xycoords='data', xytext=(xdata[ind][0], ydata[ind][0]))
self.figure_canvas.draw()
def goPrinter(self):
printer = QPrinter()
printer.A4
printer.HighResolution
printer.Color
anotherWidget= QPrintDialog(printer,self)
if(anotherWidget.exec_() != QDialog.Accepted):
return
p = QPixmap.grabWidget(self.figure_canvas)
printLabel = QLabel()
printLabel.setPixmap(p)
painter = QPainter(printer)
printLabel.render(painter)
painter.end()
# self.show()
if __name__=="__main__":
app=QApplication(sys.argv)
mw=ViewWidget()
mw.show()
sys.exit(app.exec_())