How to put dates on the x qwtplot axis in python? - python-2.7

I visited tons of pages in the internet but only have examples in C and I dont understand how to make this in python. Can someone helpme.
I use Pyqt designer and Python 2.7. I need plot data whith dates on a GUI using qwtplot.

you need a QwtScaleDraw class e.g.:
class TimeScaleDraw(QwtScaleDraw):
def __init__(self, baseTime, *args):
QwtScaleDraw.__init__(self, *args)
self.baseTime = baseTime
def label(self, value):
upTime = self.baseTime.addSecs(int(value))
return QwtText(upTime.toString())
then you modify your x axis with this code:
self.setAxisScaleDraw(
QwtPlot.xBottom, TimeScaleDraw(self.cpuStat.upTime()))
where self's base class is QwtPlot. cpuStat.upTime() returns a QTime instance. value represents one of your time data points. This code is from the cpuDemo example code.
To get this example cpuDemo working with python xy 2.7. make these changes to the imported modules:
import os
import sys
import numpy as np
from PyQt4.QtGui import (QApplication, QColor, QBrush, QWidget, QVBoxLayout,
QLabel)
from PyQt4.QtCore import QRect, QTime
from PyQt4.QtCore import Qt
from PyQt4.Qwt5 import (QwtPlot, QwtPlotMarker, QwtScaleDraw, QwtLegend, QwtPlotCurve,
QwtPlotItem, QwtText)#, QwtLegendData
then comment out all legend lines.
I adopted this code to use the QDateTime class. Here is a snippet:
from PyQt4 import QtCore, QtGui, Qt
from PyQt4 import Qwt5
class TimeScaleDraw(Qwt5.QwtScaleDraw):
def __init__(self, *args):
Qwt5.QwtScaleDraw.__init__(self,unixBaseTime *args)
self.basetime=unixBaseTime
self.fmt='h:mm\nd-MMM-yyyy'
def label(self, value):
dt = QtCore.QDateTime.fromMSecsSinceEpoch((value+self.basetime))
return Qwt5.QwtText(dt.toString(self.fmt))
...
class Ui_TabWidget(object):
def setupUi(self, TabWidget):
self.qwtPlot = Qwt5.QwtPlot()
self.qwtPlot.setAxisScaleDraw(Qwt5.QwtPlot.xBottom, TimeScaleDraw(unixBaseTime))
admire pretty picture

Related

RuntimeError: super-class __init__() of type HelloWorldWin was never called

As I was following some code example on the internet. I bump into this code.
# minimal.py
from matplotlib.backends import qt_compat
use_pyside = qt_compat.QT_API == qt_compat.QT_API_PYSIDE
if use_pyside:
from PySide import QtGui, QtCore
else:
from PyQt4 import QtGui, QtCore
class HelloWorldWin(QtGui.QMainWindow):
def __init__(self,*args, **kw):
QtGui.QMainWindow.__init__(self)
self.show()
app = QtGui.QApplication([])
win = HelloWorldWin()
app.exec_()
for the line "QtGui.QMainWindow.init(self)" I decided to change the code to super(HelloWorldWin,self).init(self) for the sake of the convenience in the future. But This one gives me the following error
RuntimeError: super-class init() of type HelloWorldWin was never called
Interestingly enough, when I take out self inside of bracket the error is gone.
I'm not sure why does it behave this way. Any help would be appreciated.

Show matplotlib plot inline in jupyter when plot is created in external function

I am running an inference algorithm and would like to show the likelihood function after each iteration. However, the plotting function is part of a package that i am importing. I've managed to cobble it together such that the plot is shown using the tkAgg backend in an external gui window, but is there any way to make it show as an inline plot? Here is what I'm using now:
Minimal Working Example
Jupyter Code
%matplotlib inline
#import matplotlib
#matplotlib.use('tkAgg')
import matplotlib.pyplot as plt
import sys
import numpy as np
sys.path.append('/path/to/file')
#______________________________________________________________
import testclass
a = testclass.test()
a.iterator()
as can be seen below this should iteratively plot a series of dots updating the plot with one dot at a time. When I run it inline I only get the full plot after it has finished running.
Class Code
import numpy as np
import matplotlib
matplotlib.use('tkAgg')
import matplotlib.pyplot as plt
import time
class test(object):
def __init__(self):
self.x = np.random.randint(0,50,size=5)
def iterator(self):
for i in range(5):
self.plotter(i)
st = time.time()
while (time.time()-st)<2:
pass
def plotter(self,i):
if not hasattr(self,'fig'):
self.fig = plt.figure()
else:
plt.close(self.fig)
self.fig = plt.figure()
#plt.ion()
self.fig.gca().plot(self.x[:i],'o')
self.fig.show()
Original Code
Notebook Code
import matplotlib
matplotlib.use('tkAgg')
import mypackage
class_instance = mypackage.myclass()
myclass.fit(n_iterations=100)
the plotting function is a bound method of the class and is called by the fit method.
Plotting Function Function
def update_plot(self,r,LLst,kkk):
if not hasattr(self,'LL_fig'):
self.LL_fig = plt.figure()
else:
plt.close(self.LL_fig)
self.LL_fig = plt.figure()
#plt.ion()
#self.LL_fig.clf()
ax = self.LL_fig.gca()
ax.plot(LLst[1:],linestyle='-',marker='.')
#plt.gca().set_xlim([0,np.max([50,kkk])])
ax.set_xlim([0,np.max([50,kkk])])
ax.set_xlabel('EM iter')
ax.set_ylabel('$\mathcal{L}( \\theta )$')
seaborn.despine(trim=True,offset=15)
#plt.draw()
self.LL_fig.show()
#display.clear_output(wait=True)
#display.display(plt.gcf())
sys.stdout.write("\riter: %s || LL: %s || message: %s" %(kkk,np.round(LLst[-1],decimals=2), r['status']))
sys.stdout.flush()
Also, if I don't close and 're-initialise' the figure each time, the plot starts coming up empty. Any help would be much appreciated!
edit:
if I try using matplotlib inline instead of tkAgg backend I get the following warning message:
UserWarning: matplotlib is currently using a non-GUI backend, so cannot show the figure
"matplotlib is currently using a non-GUI backend, "
Use the cell magic %matplotlib inline (if you aren't familiar with cell magics, just place it in a line on its on in one of your cells)

Python+Glade Set Label text

I have a little python script with a Gladefile but my code i not doing was i wanted it to.
There several issues that i can't solve. Just trying to get a date/time written on my label "DK_Tid".
But I get an error:
self.DK_Tid.set_text(dk_time)
NameError: global name 'self' is not defined
And when i have tried to move the thread out of class, there is no print, but window is showed. All sort of variation i've tried, but now i'm stuck.
No mather what i do, it won't work.
Can anyone help me?
#!/usr/bin/env python
#
# Time test deppends on test.glade
import sys, time, thread, gi
gi.require_version('Gtk', '3.0')
from gi.repository import GObject,Gtk as Gtk
gi.require_version('GdkX11', '3.0')
from gi.repository import GdkX11
from datetime import datetime, timedelta
class GTK_Main(object):
def __init__(self):
self.gladefile = ("test.glade")
self.builder = Gtk.Builder()
self.builder.add_from_file(self.gladefile)
self.builder.connect_signals(self)
## Create objects by name from glade
self.window = self.builder.get_object("window")
self.DK_Tid = builder.get_object("DK_Tid")
self.window.show_all()
# Create handles
def on_window_destroy(self, object, data=None):
Gtk.main_quit()
def UTC_time():
now = datetime.now()
new_time = now + timedelta(hours=0, minutes=0, seconds=1)
while True:
if new_time < datetime.now():
dk_time = time.strftime("%d %B %Y %H:%M:%S")
self.DK_Tid.set_text(dk_time)
print dk_time
now = new_time
new_time = now + timedelta(hours=0, minutes=0, seconds=1)
thread.start_new_thread(UTC_time())
GObject.threads_init()
GTK_Main()
Gtk.main()
Solution found by myself. :-)
Gtk is strange sometimes.
I think that i needed to put in after the if function:
while Gtk.events_pending():
Gtk.main_iteration()
But is quite some time ago i made that script.

Python Tkinter: destroy() my Toplevel() window

I don't understand what I'm doing wrong.
I'm trying to create a log in window. When you click Log in, I want to to go do stuff and after that close out and go to the main GUI.
I found a bunch of stuff online that I can't make heads or tails of. I do not want to cut and paste other people's code which I do not fully understand.
So I'd like to understand what I'm doing wrong here. To start I created a destroyWindow() method which I call from the button as just a starting point.
There is a scope issue where loginWindow does not exist within its own class. I thought the class application would get around the scope issue. I tried using 'self.' but to no avail. I tried random things I saw in other people's code. Please can someone pinpoint what I'm missing here? I get
NameError: global name 'loginWindow' is not defined
#!/Usr/bin/Python
import Tkinter,tkFileDialog,tkMessageBox
from Tkinter import *
from tkFileDialog import *
import sys, time, datetime
import pathlib
from pathlib import * #makes it really easy to travers folders if needed.
mainWindow = Tk()
mainWindow.wm_title("my prog")
mainWindow.wm_iconbitmap('fb_logo_sm.ico')
mainFrame = Frame(mainWindow)
mainFrame.grid(padx=10,pady=10)
class loginWindowClass():
def __init__(self):
loginWindow = Tkinter.Toplevel()
loginWindow.configure(bg='#22BEF2')
loginWindowFrame = Frame(loginWindow,bg='#22BEF2')
loginWindowFrame.grid(padx=90,pady=50)
loginWindow.wm_title("log in")
loginWindow.wm_iconbitmap('my.ico')
usernameLable = Tkinter.Label(loginWindowFrame,text="User Name",fg='#FFFFFF',bg='#22BEF2')
usernameLable.grid(row=1,column=2,padx=(0,5),sticky=W+S)
usernameField = Entry(loginWindowFrame)
usernameField.config(width=24)
usernameField.grid(row=2,column=2)
passwordLable =Tkinter.Label(loginWindowFrame,text="Password",fg='#FFFFFF',bg='#22BEF2')
passwordLable.grid(row=3,column=2,sticky=W+S)
passwordField = Entry(loginWindowFrame)
passwordField.config(width=24)
passwordField.grid(row=4,column=2)
loginButton = Button(loginWindowFrame, text='Log In', height=1, width=20, wraplength=100, fg='white',bg='#bbbbbb',command=self.destroyWindow).grid(row=5,column=2,pady=(10,0))
def destroyWindow(self):
loginWindow.destroy()
logwin = loginWindowClass()
mainWindow.mainloop()
Ah. 'self.' is the answer indeed.
I did not apply it everywhere. Here is the solution
#!/Usr/bin/Python
import Tkinter,tkFileDialog,tkMessageBox
from Tkinter import *
from tkFileDialog import *
import sys, time, datetime
import pathlib
from pathlib import * #makes it really easy to travers folders if needed.
mainWindow = Tk()
mainWindow.wm_title("my prog")
mainWindow.wm_iconbitmap('fb_logo_sm.ico')
mainFrame = Frame(mainWindow)
mainFrame.grid(padx=10,pady=10)
class loginWindowClass():
def __init__(self):
self.loginWindow = Tkinter.Toplevel()
self.loginWindow.configure(bg='#22BEF2')
loginWindowFrame = Frame(self.loginWindow,bg='#22BEF2')
loginWindowFrame.grid(padx=90,pady=50)
self.loginWindow.wm_title("log in")
self.loginWindow.wm_iconbitmap('my.ico')
usernameLable = Tkinter.Label(loginWindowFrame,text="User Name",fg='#FFFFFF',bg='#22BEF2')
usernameLable.grid(row=1,column=2,padx=(0,5),sticky=W+S)
usernameField = Entry(loginWindowFrame)
usernameField.config(width=24)
usernameField.grid(row=2,column=2)
passwordLable =Tkinter.Label(loginWindowFrame,text="Password",fg='#FFFFFF',bg='#22BEF2')
passwordLable.grid(row=3,column=2,sticky=W+S)
passwordField = Entry(loginWindowFrame)
passwordField.config(width=24)
passwordField.grid(row=4,column=2)
loginButton = Button(loginWindowFrame, text='Log In', height=1, width=20, wraplength=100, fg='white',bg='#bbbbbb',command=self.destroyWindow).grid(row=5,column=2,pady=(10,0))
def destroyWindow(self):
self.loginWindow.destroy()
logwin = loginWindowClass()
mainWindow.mainloop()

SVG rendering differs between Safari/Chrome/Firefox

I am dynamically generating a figure as part of a website. The figure is generated by matplotlib as part of a Django view function. Within the view function, I render the figure as an SVG and then add that SVG's content to the view's context and then render a very simple template using that context. It's a graph of temperature over time from a particular sensor.
When I view the page in a browser, everything works right, in general terms: the graph is shown in the right place and generally shows the right info. But the image looks different when viewed in Safari vs either Chrome or Firefox.
Here's how it looks in Chrome/Firefox:
And here's how it looks in Safari:
A link to the SVG itself is here.
Here's the code that is generating the SVG:
from django.views.generic import TemplateView
from mysite.models import TempReading, TempSeries
import numpy as np
import pandas as pd
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import seaborn as sbn
import StringIO
class TestView(TemplateView):
template_name = 'mysite/test.html'
def get_context_data(self, **kwargs):
upstairs = TempSeries.objects.get(name='Upstairs')
upstairstemps = upstairs.tempreading_set.all().order_by('-timestamp')
frame = pd.DataFrame(list(upstairstemps.values()))
frame.set_index('timestamp', inplace=True)
fig = Figure()
ax = fig.add_subplot(1,1,1)
frame['value'].plot(ax=ax)
ax.get_xaxis().grid(color='w', linewidth=1)
ax.get_yaxis().grid(color='w', linewidth=1)
fig.set(facecolor='w')
canvas = FigureCanvas(fig)
imgdata = StringIO.StringIO()
canvas.print_svg(imgdata)
imgstr = imgdata.getvalue()
context = super(TestView, self).get_context_data(**kwargs)
context['svgtext'] = imgstr
return context
Any thoughts on why the SVG would render differently in different browsers?