Can't inline Bokeh in IPython - python-2.7

I have the latest Bokeh and IPython installed, and I try running the following:
(all of these imports are relevant later on in the code)
import pandas as pd
import datetime
import matplotlib.pyplot as plt
import itertools as itt
import bokeh.plotting as bk
bk.output_notebook()
xs = [0,1,2,3,4,5]
ys = [x**2 for x in xs]
p.line(xs, ys, line_width=2)
p.circle(xs,ys)
bk.show(p)
After running these 2 cells, I get:
Javascript error adding output! ReferenceError: Bokeh is not defined
See your browser Javascript console for more details.
So, I run the console and see this:
ReferenceError: Bokeh is not defined Stack trace: #http://localhost:8888/static/components/jquery/jquery.min.js?v=20150304125302 line 4 > eval:1:1 .globalEval#http://localhost:8888/static/components/jquery/jquery.min.js?v=20150304125302:4:4231 .domManip#http://localhost:8888/static/components/jquery/jquery.min.js?v=20150304125302:5:21389 .append#http://localhost:8888/static/components/jquery/jquery.min.js?v=20150304125302:5:18980 OutputArea.prototype._safe_append#http://localhost:8888/static/notebook/js/outputarea.js?v=20150304125302:414:13 OutputArea.prototype.append_display_data#http://localhost:8888/static/notebook/js/outputarea.js?v=20150304125302:534:13 OutputArea.prototype.append_output#http://localhost:8888/static/notebook/js/outputarea.js?v=20150304125302:320:13 OutputArea.prototype.handle_output#http://localhost:8888/static/notebook/js/outputarea.js?v=20150304125302:234:9 CodeCell.prototype.get_callbacks/<.iopub.output#http://localhost:8888/static/notebook/js/codecell.js?v=20150304125302:456:21 Kernel.prototype._handle_output_message#http://localhost:8888/static/services/kernels/kernel.js?v=20150304125302:997:13 .proxy/i#http://localhost:8888/static/components/jquery/jquery.min.js?v=20150304125302:4:5486 Kernel.prototype._handle_iopub_message#http://localhost:8888/static/services/kernels/kernel.js?v=20150304125302:1024:13 Kernel.prototype._finish_ws_message#http://localhost:8888/static/services/kernels/kernel.js?v=20150304125302:866:17 .proxy/i#http://localhost:8888/static/components/jquery/jquery.min.js?v=20150304125302:4:5486 deserialize#http://localhost:8888/static/services/kernels/serialize.js?v=20150304125302:60:13 Kernel.prototype._handle_ws_message#http://localhost:8888/static/services/kernels/kernel.js?v=20150304125302:857:9 .proxy/i#http://localhost:8888/static/components/jquery/jquery.min.js?v=20150304125302:4:5486 outputarea.js:416
Before seeing this, bk.show(p) displayed a distorted plot, saying "Hello Word", but all the buttons were deformed.
matplotlib works fine.

This issues was addressed in https://github.com/bokeh/bokeh/issues/2024 which moved the code that loads BokehJS into output_notebook instead of just trying to do it when bokeh is imported. However, I would still recommend putting bk.output_notebook in its own ipython cell with nothing else. I am going to update the documentation to reflect this recommendation soon. The issue is that Bokeh uses IPython's "publish" mechanism to load itself, and if you put other things in a cell that also have output, it can interfere with that. Thats just the way IPython notebook works, there's not really anything else to do but to suggest putting output_notebook on its own, so it is output is guaranteed to be correct.

So, i restarted the system a few times, and started a new notebook, and suddenly everything works. i'm guessing the issue was with one of the imports, but i'm not 100% sure. now everything works perfect.

The problem here is that Javascript function loaded in IPython.core.display, ommit it and re-run your code.

Related

Why Python line plot shows : Don't have an account? plot.ly

Actually I am new in python.
When I am trying to compile the following code:
import matplotlib.pyplot as plt
import plotly.plotly as py
# Learn about API authentication here: https://plot.ly/python/getting-started
# Find your api_key here: https://plot.ly/settings/api
x = [1,2,3,4]
y = [3,4,8,6]
plt.plot(x, 'o')
plt.plot(y)
fig = plt.gcf()
plot_url = py.plot_mpl(fig, filename='mpl-line-scatter')
It shows the following message and don't give any output. :
mks#mks-H81M-S:~/Desktop/pythonPrograms$ python plot.py
Aw, snap! We don't have an account for ''. Want to try again? You can authenticate with your email address or username. Sign in is not case sensitive.
Don't have an account? plot.ly
Questions? support#plot.ly
xdg-open - opens a file or URL in the user's preferred application
Synopsis
xdg-open { file | URL }
xdg-open { --help | --manual | --version }
Use 'man xdg-open' or 'xdg-open --manual' for additional info.
mks#mks-H81M-S:~/Desktop/pythonPrograms$
I don't know what is this and how to fix it. Help.
I'm also pretty new as far as plotly on python is concerned. However, it seems to me that the problem is the fact that you are importing plotly.plotly.
To quote from the documentation
All methods in plotly.plotly will communicate with a Plotly Cloud or
Plotly Enterprise. get_figure downloads a figure from plot.ly or
Plotly Enterprise. You need to provide credentials to download
figures: https://plot.ly/python/getting-started/
To the best of my understanding, you need to import plotly and then use functions as explained in the latter half of the introduction on this link
Hope this helps
Check the official documentation.
What you are trying to do is online plotting of your graph using plotly cloud. That is the reason it is asking for authentication.
I ll suggest instead of logging in and trying to set an API Key, etc, it would be better if you do offline plotting.
The final plot gets saved as an HTML file in your local system which can be used later if needed. Here's how you do that:
import plotly as py
fig = dict( data=data, layout=layout )
py.offline.plot( fig, filename='d3-cloropleth-map' )

Bokeh tools not working in QWebView

Good afternoon
[First time to post on stackoverflow after years of reading. Exciting!]
I use bokeh to generate html code that I feed into a QWebView in a very simple PyQt4 GUI. The standard tools on top of the bokeh chart do not work in the QWebView, while they work properly if I open the same html code in any standard browser (in my case, Chrome).
Detailed example:
I am using the snippet below taken from an older Bokeh User Guide example to test the issue (the latest User Guide can be found here):
from bokeh.plotting import figure
from bokeh.resources import CDN, INLINE
from bokeh.embed import file_html
# [other code...]
f = figure()
f.circle([1, 2.5, 3, 2], [2, 3, 1, 1.5], radius=0.3, alpha=0.5)
html = file_html(f, CDN, "my plot")
the 'html' snippet is then fed into a QtWebKit.QWebView instance called 'self.web' embedded in the GUI:
self.web.setHtml(html)
The chart displays properly, however the tools are inactive:
i) the 'Pan' tool is selected and click-and-drag works to pan the chart,
ii) the 'Scroll-wheel' tool is selected but scrolling the wheel does not zoom on the chart,
iii) clicking on any other tool ('Resize', 'Box Zoom', 'Save') does not succeed in selecting the tool
Any idea of what settings are required to make the (static) bokeh html work in the QWebView?
I have searched for related issues, and tried working on the attributes of the QWebView (e.g. setting QtWebKit.QWebSettings.JavascriptEnabled to True) with no effect.
Many thanks for the help.
(the environment is: Python 2.7.8, Anaconda 2.1.0 (64-bit), PyQt4)

matplotlib style library not updating when .mplstyle files added/deleted

I'm trying to create my own matplotlib stylesheets but Python doesn't detect them. Even worse: when I moved one of the five default stylesheets (ggplot.mplstyle), Python kept reporting it was availabe.
I tried to reload the entire module but to no avail:
import matplotlib
reload(matplotlib)
from matplotlib import style as style
plt = matplotlib.pyplot
print plt.style.available
just keeps returning
[u'dark_background', u'bmh', u'grayscale', u'ggplot', u'fivethirtyeight']
How can I force a "refresh" of these styles?
P.s. I'm not a Python expert.
Just in case someone else stumbles on this post, this issue was reported and resolved here:
https://github.com/matplotlib/matplotlib/issues/3601
Basically, the style library looks for files in a subdirectory of the matplotlib config directory. On linux/osx system, this would be something like ~/.matplotlib/stylelib/<my-custom-style>.mplstyle.
Also, as #tcaswell suggested in comments, loading is done at import time, so style files added or edited after import will not work without a call to plt.style.reload_library().

Can't save figure as .eps [gswin32c is not recognized]

I'm using Enthought Canopy with PyLab(64-bit). For my report I need to use Latex (XeLaTex) and the plots are done with matplotlib.
To have an first idea I just copied the second example from http://matplotlib.org/users/usetex.html and compiled it. It looks fine and I can save it as a normal png without problems. However if i try to save it as .eps or.ps it does not work and an error appears:
invalid literal for int() with base 10: "
Additionaly in the Pylab shell it shows:
'gswin32c' is not recognized as an internal or external command, operable program or batch file'.
If I save it as .pdf I have no problems except the text is all black instead of being red and blue. This is a problem because in my plots I have two axes and I need them colorized for better readability.
If I then try to delete some lines from the example given (all text) I still cannot save it as .eps nor .ps. I can't figure out the problem and all the other topics related to this have not given me an insight. So I really need your help because I can't use .png for my report.
Thank you in advance!!!
I finally managed to solve this problem. It might look weird but maybe other people can benefit from it.
The solution might depend upon the software you use. I use Enthought Canopy (Python) and MikTeX 2.9 under W8 64bit.
If you want to output .ps and .eps files with matplotlib using the 'text.usetex': True option then you will encounter the problem posted above.
Solution:
Download and install Ghostscript (32bit) from http://www.ghostscript.com/download/gsdnld.html.
Download ps2eps-1.68.zip from http://www.tm.uka.de/~bless/ps2eps. The proceeding is given in the manual, however I like to point out the part with the environment variables. In this last step you need to go to Control Panel --> System --> Advanced system settings. Then click on the header 'Advanced' and on the bottom of the window you see 'Environment Variables' on which you click. Then you use the 'New'-Button for User Variables for USERNAME. Then you type in as variable name 'ps2eps' and for variable value you type in the actual path where you have saved the ps2eps.pl file. In my case this is 'C:\Program Files (x86)\ps2eps\bin\'. You can check if you type 'ps2eps' in the command-window.
Download xpdfbin-win-3.03.zip from http://www.foolabs.com/xpdf/download.html. You only need the file 'pdftops.exe'. However I could not assign a path like in step 2. I solved this by putting the 'pdftops.exe' in the MikTeX 2.9 folder. The exact location for me was 'C:\Program Files\MiKTeX 2.9\miktex\bin\x64'.
I was then able to save figures as .ps and have no more any error messages. Remember to use the settings proposed on http://matplotlib.org/users/usetex.html under 'postscript options'.
In myself used the following settings:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib as mpl
mpl.rc('font', **{'family':'serif', 'serif':['Computer Modern Roman'],
'monospace':['Computer Modern Typewriter']})
params = {'backend': 'ps',
'text.latex.preamble': [r"\usepackage{upgreek}",
r"\usepackage{siunitx}",
r"\usepackage{amsmath}",
r"\usepackage{amstext}",],
'axes.labelsize': 18,
#'axes.linewidth': 1,
#'text.fontsize':17,
'legend.fontsize': 10,
'xtick.labelsize': 13,
#'xtick.major.width' : 0.75,
'ytick.labelsize': 13,
'figure.figsize': [8.8,6.8],
#'figure.dpi': 120,
'text.usetex': True,
'axes.unicode_minus': True,
'ps.usedistiller' : 'xpdf'}
mpl.rcParams.update(params)
mpl.rcParams.update({'figure.autolayout':True})
(whereas many of the params are just for my own purpose later in the plots)
As a beginner I am not well informed about the dependence from the 'backend' used if you are running a script from your python console. I however used this without any --pylab settings in before and I do not know if one needs to switch the backend manually if he is working already in a console with a specific matplotlib backend.
I had the same problem and my problem was a font adjustment in the python code that is :
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
when I remove this iit works fine and now i can save eps.
So be sure that any shortest working example is working for you or not then check the font and other style edits in your code. This may help.

TextMate: Preview in Firefox without having to save document first?

Using TextMate:
Is it possible to assign a shortcut to preview/refresh the currently edited HTML document in, say, Firefox, without having to first hit Save?
I'm looking for the same functionality as TextMate's built-in Web Preview window, but I'd prefer an external browser instead of TextMate's. (Mainly in order to use a JavaScript console such as Firebug for instance).
Would it be possible to pipe the currently unsaved document through the shell and then preview in Firefox. And if so, is there anyone having a TextMate command for this, willing to share it?
Not trivially. The easiest way would be to write the current file to the temp dir, then launch that file.. but, this would break any relative links (images, scripts, CSS files)
Add a bundle:
Input: Entire Document
Output: Discard
Scope Selector: source.html
And the script:
#!/usr/bin/env python2.5
import os
import sys
import random
import tempfile
import subprocess
fname = os.environ.get("TM_FILEPATH", "Untitled %s.html" % random.randint(100, 1000))
fcontent = sys.stdin.read()
fd, name = tempfile.mkstemp()
print name
open(name, "w+").write(fcontent)
print subprocess.Popen(["open", "-a", "Firefox", name]).communicate()
As I said, that wont work with relative resource links, which is probably a big problem.. Another option is to modify the following line of code, from the exiting "Refresh Browsers" command:
osascript <<'APPLESCRIPT'
tell app "Firefox" to Get URL "JavaScript:window.location.reload();" inside window 1
APPLESCRIPT
Instead of having the javascript reload the page, it could clear it, and write the current document using a series of document.write() calls. The problem with this is you can't guarantee the current document is the one you want to replace.. Windows 1 could have changed to another site etc, especially with tabbed browsing..
Finally, an option that doesn't have a huge drawback: Use version control, particularly one of the "distributed" ones, where you don't have to send your changes to a remote server - git, mercurial, darcs, bazaar etc (all have TextMate integration also)
If your code is in version control, it doesn't matter if you save before previewing, you can also always go back to your last-commited version if you break something and lose the undo buffer.
Here's something that you can use and just replace "Safari" with "Firefox":
http://wiki.macromates.com/Main/Howtos#SafariPreview
Open the Bundle Editor (control + option + command + B)
Scroll to the HTML Bundle and expand the tree
Select "Open Document in Running Browser(s)"
Assign Activation Key Equivalent (shortcut)
Close the bundle editor
I don't think this is possible. You can however enable the 'atomic saves' option so every time you alt tab to Firefox your project is saved.
If you ever find a solution to have a proper Firefox live preview, let us know.