Plotly R not working with Jupyter notebook - python

I want to incorporate Plotly graphs in my Jupyter notebook but I'm getting a 404 error when I try to display a graph:
According to this post
import sys; print(sys.executable)
Gives me this location for Python. I have the two Pandoc files in this directory as and all the files needed as mentioned on Plotly's page.
C:\Users\name\AppData\Local\Continuum\Anaconda3\python.exe
I have also tried reinstalling Anaconda and Pandoc but I'm still getting this error. Any thoughts?

Do you have a plotly account? You may need to login into it within your notebook with something similar to this:
import plotly
plotly.tools.set_config_file(plotly_domain='domain')
from plotly import __version__
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
import plotly.plotly as py
print __version__ # requires version >= 1.9.0
import plotly.graph_objs as go
init_notebook_mode() # run at the start of every ipython notebook to use plotly.offline
# this injects the plotly.js source files into the notebook
py.sign_in(username='xxxx', api_key='xxxx')

I have the same issue in MacOS. In the console, it can be seen that it's looking for .html.embed but the file which is created is .html.
I have tried,
1) reinstalling Pandocs
2) Had to reinstall Cairo as package pbdZMQ was not getting installing properly.
This is the workaround I did,
p <- plot_ly(ds, x = x, y = y, mode = "markers", group = group, size = size)
htmlwidgets::saveWidget(as.widget(p), "index.html")
rawHTML <- paste(readLines("index.html"), collapse="\n")
display_html(rawHTML)
This is not the best solution, but for the time being this works for me.

Related

How can I do a Static Image Export on Google Colab

I'm trying to export an image I've created with plotly as a .svg file.
This is the code I'm running to export it:
fig.write_image("/content/fig1.svg")
This is the error I'm getting:
I've entered in the github page of Orca and tried to use the installation codes they suggest but neither one worked.
You can install orca with the following code. (a library I wrote)
!pip install kora -q
import kora.install.orca
Then it can write_image
import plotly.graph_objects as go
fig = go.Figure( go.Scatter(x=[1,2,3], y=[1,3,2] ) )
fig.write_image("image.png")
from IPython.display import Image
Image("image.png")
If you prefer to install orca yourself
import os
from urllib.request import urlretrieve
url = "https://github.com/plotly/orca/releases/download/v1.2.1/orca-1.2.1-x86_64.AppImage"
orca = '/usr/local/bin/orca'
urlretrieve(url, orca)
os.chmod(orca, 0o755)
os.system("apt install xvfb libgconf-2-4")

ImportError: `iplot` can only run inside an IPython Notebook

When I run the following code in PyCharm on a Mac:
import numpy as np
import pandas as pd
from subprocess import check_output
print(check_output(["ls", "../input"]).decode("utf8"))
import time
import copy
import numpy as np
import pandas as pd
import chainer
import chainer.functions as F
import chainer.links as L
from plotly import tools
from plotly.graph_objs import *
from plotly.offline import init_notebook_mode, iplot, iplot_mpl
init_notebook_mode()
data = pd.read_csv('../input/Data/Stocks/goog.us.txt')
data['Date'] = pd.to_datetime(data['Date'])
data = data.set_index('Date')
print(data.index.min(), data.index.max())
data.head()
There were some errors:
UserWarning: Accelerate has been detected as a NumPy backend library.
vecLib, which is a part of Accelerate, is known not to work correctly with Chainer.
We recommend using other BLAS libraries such as OpenBLAS.
For details of the issue, please see
https://docs.chainer.org/en/stable/tips.html#mnist-example-does-not-converge-in-cpu-mode-on-mac-os-x.
Please be aware that Mac OS X is not an officially supported OS.
''') # NOQA
Traceback (most recent call last):
File "/Users/yindeyong/Desktop/PythonProjects/pythonstock/DQNStcok.py", line 33, in <module>
init_notebook_mode()
File "/Users/yindeyong/Desktop/PythonProjects/envs/stockenv/lib/python3.6/site-packages/plotly/offline/offline.py", line 250, in init_notebook_mode
raise ImportError('`iplot` can only run inside an IPython Notebook.')
ImportError: `iplot` can only run inside an IPython Notebook.
Process finished with exit code 1
I'm new in Chainer and DQN. Could anyone help me edit this code to make it work? Thank you so much!
It seems like you're trying to run plotly interactive functions (i prefix) in a normal Python code (i.e. not IPython Notebook). iplot provides an interactive graph with which you can play inside the notebook.
I'd start with removing iplot import and replacing it with normal plot. Also, remove iplot_mpl and init_notebook_mode from your imports.
You can install 'ipython' in the virtual environment and then try running it directly from the terminal.
Activate the virtual environment
pip3 install ipython
python3 prog.py
Worked in my case.

How to save plotly offline by running my script

I am using below code in my jupyter notebook.
import pandas as pd
import numpy as np
%matplotlib inline
from plotly import __version__
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
print(__version__)
import cufflinks as cf
init_notebook_mode(connected=True)
cf.go_offline()
df2 = pd.DataFrame({'Category':['A','B','C'],'Values':[22,33,45]})
df2.iplot(kind='bar',x='Category',y='Values', asImage=True, filename='bar')
Its giving an image to save while running in notebook, and i saved this code in bar.py and I ran python bar.py it's giving me the error You must be authenticated to generate an image via json.
I want to run my script which will save my bar plot as image in the same location, I can't use notebook because this scripts is going to be in my automation.
The Plotly graphs are generated in HTML+Javascript. When you run in Jupyter Notebook, you're in a web application that runs in the browser already, so it can render them directly.
When running on the command line, it can generate an HTML file with the graph for you, but you'll need to open that in the browser to have it rendered.
The Plotly Offline documentation page explains this. The text there says that you can save images only when running in Notebook. There seems to be a way to generate an image using online mode - you will need a Plotly account and network access for that.
You might want to consider a different plot library for automated offline work, which does not require network access or running an HTML user agent.
tried this https://plot.ly/python/static-image-export/ and volla!
though I had to struggle with orca.
import pandas as pd
import numpy as np
%matplotlib inline
from plotly import __version__
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.graph_objs as go
import plotly.io as pio
print(__version__)
import cufflinks as cf
init_notebook_mode(connected=True)
cf.go_offline()
fig = go.Figure()
fig.add_bar(x=df2['Category'],y=df2['Values'])
iplot(fig)
pio.write_image(fig, 'fig1.png')

How to run externally

I have plotted a graph from a CSV file using SPYDER from PYTHON
Here is my code
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv('GM_NB_Replica_Test.csv', skiprows=8)
data = df.ix[:,19:116].T
data.columns=df['SN']
data.plot()
plt.show()`
Here is my Output inside the python console:
How do i get this to run externally (Not inside python console, and not in new python console)
I have already tried changing the run settings (See photo below)
However it just gives me a black Python CMD and then no graph.
any thoughts?
current error when running in CMD
From your command prompt (CMD):
cd C://location_of_your_script
python script.py

what is this color map? cmap=mglearn.cm3

I try to run the following code but it gives the following error in recognistion of mglearn color map.
grr = pd.scatter_matrix( ...., cmap=mglearn.cm3)
ErrorName: name 'mglearn' is not defined
I should add pd is Anaconda Pandas package imported as pd but does not recognize the color map mglearn.cm3
Any suggestions?
Open Anaconda prompt and execute pip install mglearn
After that just import mglearn
import pandas as pd
import mglearn
iris_dataframe = pd.DataFrame(X_train, columns=iris_dataset.feature_names)
grr = pd.scatter_matrix(iris_dataframe, c=y_train, figsize=(15, 15), marker='o',s=60, alpha=0.8, hist_kwds={'bins': 10},cmap=mglearn.cm3)
Concerns the code for the book - Introduction to Machine Learning with Python
At the top of the Code for the book (notebooks, etc.) there is a package folder named - mglearn. It contains, as its fist .py file - init.py.
It therefore allowed me to simply copy/paste the folder - mglearn, into my
C:\Users\Ernesto\Anaconda3 folder and afterwards type - import mglearn - in my Spyder 3.5 editor.
Then the line:
grr = pd.scatter_matrix(iris_dataframe,
c=y_train,
figsize=(15, 15),
marker='o',
hist_kwds={'bins': 20},
s=60,
alpha=0.8,
cmap=mglearn.cm3)
prints the scatter_matrix just as in the book.
conda install pip(because conda install mglearn will give a error)
pip install mglearn
grr = pd.plotting.scatter_matrix( ...., cmap=mglearn.cm3)
if you still can't see the output then you might have missed %matplotlib inline
You need to install mglearn package. You can do that by running the below command in your Command Prompt or in the terminal (Anaconda/ any other IDE that has support for Terminal).
pip install mglearn
For more details on mglearn package visit: enter link description here
if you are working in jupyter notebook just use cmap='PuBu' in scatter_matrix()

Categories