How to get basic interactive pyqtgraph plot to work in IPython REPL or Jupyter console? - ipython

Typing
import pyqtgraph as pg
pg.plot([1,2,3,2,3])
into the standard Python REPL opens a window containing a plot of the data. Typing exactly the same code into the IPython REPL or the Jupyter console, opens no such window.
[The window can be made to appear by typing pg.QtGui.QApplication.exec_(), but then the REPL is blocked.
Alternatively, the window appears when an attempt is made to exit the REPL, and confirmation is being required.
Both of these are highly unsatisfactory.]
How can basic interactive pyqtgraph plotting be made to work with the IPython REPL?
[The described behaviour was observed in IPython 5.1.0 and Jupyter 5.0.0 with Python 3.5 and 3.6 and PyQt4 and PyQt5 (no PySide)]

As sugested by #titusjan, the solution is to type
%gui qt
(or some variation on that theme: see what other options are available with %gui?) in IPython before issuing any pyqtgraph (or PyQt in general) commands.

I had a problem with matplotlib in Jupyter Notebook. It was not fast enough and I found the navigation to be deficient. I got pyqtgraph to work using tips I found here. OMG! This is a great tool. The navigation and the speed you get is awesome.
Thought I would share my solution here.
%gui qt5
from PyQt5.Qt import QApplication
# start qt event loop
_instance = QApplication.instance()
if not _instance:
_instance = QApplication([])
app = _instance
import pyqtgraph as pg
# create and and set layout
view = pg.GraphicsView()
view.setWindowTitle('Your title')
layout = pg.GraphicsLayout()
view.setCentralItem(layout)
view.show()
# Set white graph
pg.setConfigOptions(antialias=True)
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
# add subplots
p0 = layout.addPlot(0,0)
p0.addLegend()
p0.plot([1,2,3,4,5], pen='b', name='p0')
p1 = layout.addPlot(1,0)
p1.addLegend()
p1.plot([2,2,2,2,], pen='r', name='p1')
p2 = layout.addPlot(1,0)
p2.addLegend(offset=(50, 0))
p2.plot([-1,0,1,1,], pen='g', name='p1.1')
p2.hideAxis('left')
p2.showAxis('right')
You will get a pop up window like that

Related

Convert greek latex symbol in the jupyter-lab text editor

In Jupyter Notebooks you can type, for example \alpha and hit the tab key and the \alpha changes into α. This is a pretty cool feature. Unfortunately, it doesn't work in the jupyter-lab editor. Any reason why that doesn't work? Or do I need to set a preference somewhere?
if you type $\alpha$ it will be rendered as the greek letter thanks to latex
Although the answer of #joelostblom works fine, you can simply install the LaTeXStrings Julia package to enable the \alpha [tab] feature without needing to spawn an IPython kernel.
using Pkg
Pkg.add("LaTeXStrings")
This feature is provided by the IPython kernel, not the Jupyter Notebook. The kernel provides TAB completion by looking up the latex (or latex-like) symbol in this dictionary (originally from Julia) and then inserts its value (the corresponding Unicode character). As such, there needs to be an active IPython kernel to provide the TAB completion (here is the PR that added the functionality to IPython in case you want to read more about it).
An IPython kernel is automatically started with the notebook and used when running cells, but this is not the case when editing a text file (which is also why there is no TAB completion for other things such as imports, etc). You can start one manually by right clicking inside a Python text file and selecting "Create console for editor". After that autocompletion works just as in the notebook, including Greek latex symbols.

Complete command from history in ipython

For reasons outside of my control I'm stuck using python 2.6.6 and IPython 0.10.2. I also normally use the tcsh shell, and have gotten quite used to completing a command from the history using <A-p> (i.e. pressing the ALT key and p). However, this doesn't work in IPython. I know I can press <C-r> and then start typing a command, but what inevitably is happening is that I start a command, press <A-p>, get a colon indicating some weird state, then exit out of that state, delete my command, press <C-r> then search for my command. It's getting rather irritating. Is there any way to make <A-p> complete my already started command by relying on the history?
Ouch, this is an old version of IPython, Python (and pip). The bad news is I don't have much experience with such an old version of IPython, the good new is; it was way simpler at that time.
Most of the shortcut and feature are provided using readline, and the python bindings of stdlib. Meaning that most likely what you are trying to configure is readline itself and not only IPython; so you can find more information on that outside of IPython !
The secret is to grep in the source-code for parse_and_bind, then you'll find the following example configuration, leading me to change the ~/.ipython/ipy_user_conf.py to be like so at around line 99 (all indented an extra 4 space to be in the main() function):
import readline
readline.parse_and_bind('set completion-query-items 1000')
readline.parse_and_bind('set page-completions no')
rlopts = """\
tab: complete
"\C-l": possible-completions
set show-all-if-ambiguous on
"\C-o": tab-insert
"\M-i": " "
"\M-o": "\d\d\d\d"
"\M-I": "\d\d\d\d"
"\C-r": reverse-search-history
"\C-s": forward-search-history
"\C-p": history-search-backward
"\C-n": history-search-forward
"\e[A": history-search-backward
"\e[B": history-search-forward
"\C-k": kill-line
"\C-u": unix-line-discard"""
for cmd in rlopts.split('\n'):
readline.parse_and_bind(cmd)
The repetition of commands make me think that what \C,\M or [e mean might be system dependant. I would bet on \C being Control, and \M being Meta (Alt, Opt), but at least one of these line did the trick for me (and also now tab allows to complete). See also man readline for the list of commands you can bind to what, and enjoy! Hoping you can upgrade to Python 3 and IPython 6 at some point.
[Edit]
See Eric Carlsen second comment under this answer for how it was resolved.

save_file() not giving 'already exists' messagebox

I'm trying to use the save_file() from traitsui.file_dialog, and I'm having a problem...the really odd thing is that if I run my code in Visual Studio (using PTVS), it works just fine!
Here's the problem as I see it...
When I use the dialog created by save_file() to pick an already existing file, I get NotImplemented errors in the iPython window of the Canopy editor, and I think it indicates that I don't have a FileExistsHandler in my code (I'm still in the early phases of learning Python/Canopy/Traits, so I may be all wet here :)). I never get a 'File Already Exists' popup either.
However, when I run the same code from inside Visual Studio using PTVS, I do get the 'File Already Exists' popup with the option to accept it or cancel.
Why does the PTVS version work, and (more importantly) how can I get my Canopy Editor version to work???
Thanks for any hand-holding anyone can supply :)
Steve
Steve, one simple thing to try in the Canopy preferences dialog's Python tab would be changing the GUI backend from Qt to WX.
Updating:
A somewhat more attractive and performant solution would be to continue using Qt but to use the file dialogs from pyface (pyface.api.FileDialog (Qt-specific; for the API, see https://github.com/enthought/pyface/blob/master/pyface/i_file_dialog.py).
Further Update...
Here's a simple block of code that works fine when using WX as the Python backend, but it has problems running using Qt:
from traitsui.file_dialog import save_file, TextInfo
import os
def SaveFile ( filename ):
""" Handles the user clicking the 'SaveAs...' button.
"""
if not os.path.isfile(filename): # if the file doesn't exist, just put the path into the file_name so I start in the same directory
(filename, dummyname) = os.path.split(filename)
filename = save_file( extensions = TextInfo(),
file_name = filename,
title = 'Save File As...',
)
return filename
newfile = SaveFile('C:\\temp\\already_there.txt')
If you run this using WX, you get the pop-up 'File already exists...' dialog with OK/Cancel buttons...running using Qt on the backend produces no pop-up, and NotImplemented errors in the iPython window :( (If I type in a new, non-existing filename, the save_file works correctly)
I really like the look of Qt screens, and someone told me that WX is for Windows only (I'm not sure of that, I haven't checked)
Is there a way I can get the save_file() to work correctly and error-free under Qt?

Configure pointer focus properties of Matlab's command window

I'm running Matlab 2013a, under Linux, using Xmonad (using the XMonad.Config.Xfce package).
This problem occurs whether the command window is docked or not.
The command window prompt does not get the keyboard focus unless the pointer is located
over the command window.
Is there a way to get the Matlab command window to have focus behaviour just like other normal windows, like a terminal?
Most important: I'd like to have the keyboard focus follow the window focus,
and not require any special positioning of the pointer, so that I can just "Alt-Tab" around my windows and have the command window get the keyboard focus. All of the resources I've found so far relate to programmatic control of focus; I'm just trying to improve my user experience in an interactive session.
To get keyboard focus on the Command Window, include the following in your xmonad.hs
import XMonad.Hooks.SetWMName
import XMonad.Hooks.ManageHelpers
and configure your ManageHook as follows
myManageHook = composeAll . concat $
[ [appName =? a --> doCenterFloat | a <- myFloatAS ]
, (your other hooks)
] where
myFloatAS = ["MATLAB"]
Finally, include setWMName "LG3D" in your startupHook. See here for a full xmonad.hs configuration which uses this (this is where I found the solution). If you have other Java apps that don't get focus as they should you can add them to the myFloatAS list.
It's a problem in the built-in java.
If i run:
export MATLAB_JAVA=/usr/lib/jvm/java-7-openjdk/jre
matlab -desktop
Matlab works as expected.
I ran into this problem, running MATLAB2014a. I set up setWMName "LG3D" but still i couldn't get focus on my window. I had to click on the focused window to get the cursor, and sometimes the situation was even worse and I had to click on random places till i get my cursor back. This wouldn't happen on MATLAB2010. What worked for me was to use the native version of java as describe above.
In the end, i used the following bash script to start matlab8:
#!/bin/bash
export MATLAB_JAVA=/usr/lib/jvm/java-7-openjdk-amd64/jre/
/usr/local/bin/matlab8 -desktop -nosplash

pydev Ipython console freezing when paging

If in the pydev 2.5 with Ipython console 0.11 I write:
import numpy
numpy?
I get the documentation for numpy and as it's longer than the screen it gets paged showing the message:
---Return to continue, q to quit---
However no matter what keys I press it'll stay there. typically I'll have to restart the console to continue.
Is this a bug?
It seems that the console is not sending the key press to actually perform the paging.
A workaround is to redefine the ipython paging function to never actually page.
Add the following code to the 'Initial interpreter commands' (PyDev -> Interactive Console)
from IPython.core import page
def nopage(strng, start=0, screen_lines=0, pager_cmd=None):
print(strng)
page.page = nopage