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' )
Related
I'm struggling to get a script working and wondering if anyone else has successfully done this.
I'm using Glue to execute a spark script and am trying to use the NLTK module to analyze some text. I've been able to import the NLTK module by uploading it to s3 and referencing that location for the Glue additional python module config. However, I'm using the word_tokenize method which requires the punkt library to be downloaded in the nltk_data directory.
I've followed this (Download a folder from S3 using Boto3) to copy the punkt files to the tmp directory in Glue. However, if I look into the tmp folder in an interactive glue session I don't see the files. When I run the word_tokenize method I get an error saying that the package cant be found in the default locations (variations of /usr/nltk_data).
I'm going to move the required files into the nltk package in s3 and try to try to re-write the nltk tokenizer to load the files directly instead of the nltk_data location. But wanted to check here first if anyone was able to get this working as this seems fairly common.
I have limited experience with NLTK, but I think the nltk.download() will put punkt in the right spot.
import nltk
print('nltk.__version__', nltk.__version__)
nltk.download('punkt')
from nltk import word_tokenize
print(word_tokenize('Glue is good, but it has some rough edges'))
From the logs
nltk.__version__ 3.6.3
[nltk_data] Downloading package punkt to /home/spark/nltk_data...
[nltk_data] Unzipping tokenizers/punkt.zip.
['Glue', 'is', 'good', ',', 'but', 'it', 'has', 'some', 'rough', 'edges']
I wanted to follow up here in case anyone else encounters these issues and can't find a working solution.
After leaving this project alone for a while I finally came back and was able to get a working solution. Initially I was adding my tmp location to the nltk_data path and downloading the required packages there. However, this wasnt working.
nltk.data.path.append("/tmp/nltk_data")
nltk.download("punkt", download_dir="/tmp/nltk_data")
nltk.download("averaged_perceptron_tagger", download_dir="/tmp/nltk_data")
Ultimately, I believe the issue was that the file I needed from punkt was not available on the worker nodes. Using the addFile method I was finally able to use nltk data.
sc.addFile('/tmp/nltk_data/tokenizers/punkt/PY3/english.pickle')
The next issue I had was that I was trying to call a UDF function from a .withColmn() method to get the nouns for each row. The issue here is that withColummn requires that a column be passed but nltk will only work with string values.
Not working:
df2 = df.select(['col1','col2','col3']).filter(df['col2'].isin(date_list)).withColumn('col4', find_nouns(col('col1'))
In order to get nltk to work I passed in my full dataframe and looped over every row. Using collect to get the text value of the row then building a new dataframe and returning that with all the original columns plus the new nltk column. To me this seems incredible inefficient but I wasn't able to get a working solution without it.
df2 = find_nouns(df)
def find_nouns(df):
data = []
schema = StructType([...])
is_noun = lambda pos: pos[:2] == 'NN'
for i in range(df.count()):
row = df.collect()[i]
tokenized = nltk.word_tokenize(row[0])
data.append((row[0], row[1], row[2], [word for (word, pos) inn nltk.pos_tag(tokenized) if is_noun(pos)]))
df2 = spark.createDataFrame(data=data, schema=schema)
return df2
I'm sure there's a better solution out there, but I hope this can help someone get their project to an initial working solution.
I am trying to add an external locale directory from the pycountry package.
Before initializing Flask Babel, I do the following:
import pycountry
app.config['BABEL_TRANSLATION_DIRECTORIES'] = 'translations;' + pycountry.LOCALES_DIR
But alas, this does not seem to be enough. For example, gettext('Germany') will not find the translation.
I think the problem might be how translations are structured in pycountry.
~/.local/lib/python3.5/site-packages/pycountry/locales/pt/LC_MESSAGES$ ls
iso15924.mo iso3166-3.mo iso4217.mo iso639-3.mo
iso3166-1.mo iso3166.mo iso639_3.mo
Do I need to specify I want, e.g., the iso3166 file? Please see the following reference.
Reference: pycountry locale documentation section
I also needed to load pycountry locale with flask babel.
To do that, I look into flask-babel get_translations() about how they load translations.
Anyway, I have something working putting this somewhere in your app.
def hack_country_gettext(string):
translations = support.Translations()
catalog = translations.load(pycountry.LOCALES_DIR, [get_locale()], 'iso3166')
translations.merge(catalog)
return translations.ugettext(string)
and instead of _('Germany') use the hack function hack_country_gettext('Germany')
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)
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.
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.