How to show the charts(linear) using Plotly? - python

I am using the below the script in python:
from plotly.offline import init_notebook_mode, iplot
import plotly.plotly as py
from plotly.graph_objs import *
from plotly.plotly.plotly import image
X=[1,2,3]
Y=[1,2,3]
fig = {'data': [{'x': X, 'y': Y, 'type': 'bar'}]}
#iplot([{"x": X, "y": Y}])
image.ishow(fig, 'png', scale=3)
I started ipython-notebook in ubuntu-PC also,but I am not able to visualize the image created or the chart plotted.
The Output is coming like this when I uncommented iplot statement:
and it returns raise exceptions.PlotlyError(return_data['error'])
KeyError: 'error .
How to plot the using plot and how to see that?

My first thought is you haven't told plotly to work in notebook mode with:
init_notebook_mode()
You imported it but never ran it.
From: https://plot.ly/python/offline/

Related

UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail

I am trying to return the data list and plot. They do display in the HTML code instead of web page. When I look at the terminal it shows "UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail."
from io import BytesIO
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
def extract(request):
if request.method == 'POST':
if request.FILES.get('document'):
file = request.FILES['document']
if 'data' in request.POST:
data = df = pd.read_excel(file)
mpl.rcParams['agg.path.chunksize'] = 10000
plt.plot(data["time"], data["make"], label='male')
plt.plot(data["time"], data["female"], label='female')
plt.xlabel('T')
plt.ylabel('M and F')
plt.legend()
buffer = BytesIO()
plt.savefig(buffer, format='png')
buffer.seek(0)
image_png = buffer.getvalue()
buffer.close()
graphic = base64.b64encode(image_png)
graphic = graphic.decode('utf-8')
dic_result = {'graphic': graphic}
dataa = []
for index in range(len(data["make"])):
data.append(tuple(dataa["male"][index], dataa["female"][index]))
return render(request, 'bothdata.html', {'data': dataa}, dic_result)
return render(request, 'extract.html')
It's just warning, it will run but can be a really painful problem. I'm not exactly an expert but I'm having the same warning, and it can be worse if you try to use matplotlib in a Thread besides Main Thread. For some reason matplotlib don't work well on Threads, which can cause your aplication to crash.
try this, it worked for me
import matplotlib
matplotlib.use('agg')
Agg, is a non-interactive backend that can only write to files.
For more information and other ways of solving it see https://matplotlib.org/stable/users/explain/backends.html

I got: chart_studio.exceptions.PlotlyRequestError: Authentication credentials were not provided

I am working locally(in my pc) just testing and learning PLOTLY 3.7.5.
with anaconda env active.
The code example is given by plotly
Code:
import plotly.plotly as py # Here all begins (Look)
# import chart_studio.plotly as py # inted of the line bellow (optional to try)
import plotly.graph_objs as go
import pandas as pd
from datetime import datetime
if __name__ == '__main__':
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
trace = go.Ohlc(x=df['Date'],
open=df['AAPL.Open'],
high=df['AAPL.High'],
low=df['AAPL.Low'],
close=df['AAPL.Close'])
data = [trace]
py.iplot(data, filename='simple_ohlc')
note (Look): I got the warning error:
'please install the chart-studio package and use the chart_studio.plotly module instead.'
You need plotly's offline mode to obviate authentication - following https://stackoverflow.com/a/44694854/1021819, rather do:
from plotly.offline import iplot
use below line of code before hitting pilot
cf.go_offline() #will make cufflinks offline
cf.set_config_file(offline=False, world_readable=True)
import pandas as pd
import numpy as np
%matplotlib inline
import plotly.graph_objs as go
from plotly.offline import plot
import chart_studio.plotly as py
import cufflinks as cf
cf.go_offline()
from plotly.offline import download_plotlyjs, init_notebook_mode, plot,iplot
init_notebook_mode(connected='true')
df = pd.DataFrame(np.random.randn(100,4),columns='A B C D'.split())
df.head()
df.iplot(kind='box')
Basics for starting Plotly and Cufflinks section:
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 cufflinks as cf
init_notebook_mode(connected=True)
cf.go_offline()
Call these two below library automatically problem will be solved
import chart_studio.plotly as py

scatter plot on map in django app raises basemap error

I created a scatter plot on indian map in jupyter notebook but when i am trying to run the same code in my djnago app. It raises
ModuleNotFoundError: No module named 'mpl_toolkits.basemap'
Here's the code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
# make up some data for scatter plot
lats = np.random.randint(6, 37, size=50)
lons = np.random.randint(68, 97, size=50)
fig = plt.gcf()
fig.set_size_inches(8, 6.5)
m = Basemap(projection='cyl', \
llcrnrlat=6., urcrnrlat=37., \
llcrnrlon=68., urcrnrlon=97., \
lat_ts=20, \
resolution='c',epsg=3857)
m.bluemarble(scale=1)
m.drawcoastlines(color='white', linewidth=0.2)
m.drawmapboundary(fill_color='#D3D3D3')
x, y = m(lons, lats)
plt.scatter(x, y, 10, marker='o', color='Red')
plt.show()
I am using the same conda interpreter in my django app. whats is the reason for this error ?
I use Anaconda under Win10. With a different OS or installation the solution may be different for you, but I can try to sketch the path.
You have to install Basemap. See here and here. For me conda install -c conda-forge basemap-data-hires did work.
When importing from mpl_toolkits.basemap import Basemap I got an error: KeyError: PROJ_LIB. Following the experiences here you must find a directory share with epsg inside. It is expected to be in the conda or the anaconda directory.
I did a search in my Anaconda3-dirctory and have found this path: "C:\Anaconda3\Library\share"
Then the following code did work for me (and your code gives a nice picture too :-) :
import os
proj_lib = "C:\Anaconda3\Library\share"
os.environ["PROJ_LIB"] = proj_lib
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
plt.figure(figsize=(8, 8))
m = Basemap(projection='ortho', resolution=None, lat_0=50, lon_0=-100)
m.bluemarble(scale=0.5);

How to plot using plotly with offline mode out not in iPython notebooks?

I need to plot my data using plotly, But this code doesn't give me any result, I display my data, but without any figure:
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
data_t = []
for mac, dico_data in dict_info.items():
data_t.append(go.Scatter( x= dico_data['asn'], y= dico_data["time"], name=mac ))
print (data_t)
data = data_t
iplot(data_t)
Try using:
init_notebook_mode(connected=True)
Or try using the inline mode in notebooks:
py.init_notebook_mode()
And if you are using it out of a notebook, try the following example:
import plotly
import plotly.graph_objs as go
plotly.offline.plot({
"data": [go.Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
"layout": go.Layout(title="hello world")
}, auto_open=True)
Read more in the plotly documentation: https://plot.ly/python/offline/
Issue:
Due to inbuilt restriction in browser, you need to install
plotly-extension
Solution:
Install it if missing with:
jupyter labextension install #jupyterlab/plotly-extension
Reference:
https://jupyterlab.readthedocs.io/en/stable/user/extensions.html

Plotly choropleth works in online but not offline mode [duplicate]

I am am trying out colaboratory with plotly notebook mode - I open a new notebook, copy and paste the following simple example from plotly's documentation, but don't see an output. There is a large blank in the output space where the plot whould normally be.
This works fine in my local notebook (which is a newer version of plotly, but per their docs offline mode should work with the google colab version)
Any ideas?
import plotly
from plotly.graph_objs import Scatter, Layout
plotly.offline.init_notebook_mode(connected=True)
plotly.offline.iplot({
"data": [Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
"layout": Layout(title="hello world")
})
plotly version 4.x
As of version 4, plotly renderers know about Colab, so the following is sufficient to display a figure in both Colab and Jupyter (and other notebooks like Kaggle, Azure, nteract):
import plotly.graph_objects as go
fig = go.Figure( go.Scatter(x=[1,2,3], y=[1,3,2] ) )
fig.show()
plotly version 3.x
Here's an example showing the use of Plotly in Colab. (Plotly requires custom initialization.)
https://colab.research.google.com/notebook#fileId=14oudHx5e5r7hm1QcbZ24FVHXgVPD0k8f
You need to define this function:
def configure_plotly_browser_state():
import IPython
display(IPython.core.display.HTML('''
<script src="/static/components/requirejs/require.js"></script>
<script>
requirejs.config({
paths: {
base: '/static/base',
plotly: 'https://cdn.plot.ly/plotly-latest.min.js?noext',
},
});
</script>
'''))
And call it in each offline plotting cell:
configure_plotly_browser_state()
simply pass "colab" as the value for the parameter renderer in fig.show(renderer="colab")
example :
import plotly.graph_objects as go
fig = go.Figure(
data=[go.Bar(y=[2, 1, 3])],
layout_title_text="A Figure Displayed with the 'colab' Renderer"
)
fig.show(renderer="colab")
Solution
import plotly.io as pio
pio.renderers.default = "colab"
You need to change the default render. Here is an excerpt from the documentation.
https://plot.ly/python/renderers/#setting-the-default-renderer
The current and available renderers are configured using the
plotly.io.renderers configuration object. Display this object to see
the current default renderer and the list of all available renderers.
>>>import plotly.io as pio
>>>pio.renderers
Renderers configuration
-----------------------
Default renderer: 'notebook_connected'
Available renderers:
['plotly_mimetype', 'jupyterlab', 'nteract', 'vscode',
'notebook', 'notebook_connected', 'kaggle', 'azure', 'colab',
'cocalc', 'databricks', 'json', 'png', 'jpeg', 'jpg', 'svg',
'pdf', 'browser', 'firefox', 'chrome', 'chromium', 'iframe',
'iframe_connected', 'sphinx_gallery']
You need to add a method in order to use Plotly in Colab.
def enable_plotly_in_cell():
import IPython
from plotly.offline import init_notebook_mode
display(IPython.core.display.HTML('''<script src="/static/components/requirejs/require.js"></script>'''))
init_notebook_mode(connected=False)
This method must be executed for every cell which is displaying a Plotly graph.
Sample:
from plotly.offline import iplot
import plotly.graph_objs as go
enable_plotly_in_cell()
data = [
go.Contour(
z=[[10, 10.625, 12.5, 15.625, 20],
[5.625, 6.25, 8.125, 11.25, 15.625],
[2.5, 3.125, 5., 8.125, 12.5],
[0.625, 1.25, 3.125, 6.25, 10.625],
[0, 0.625, 2.5, 5.625, 10]]
)
]
iplot(data)
Reference: https://colab.research.google.com/notebooks/charts.ipynb#scrollTo=WWbPMtDkO4xg
configure_plotly_browser_state() can be executed before running every cell by using IPython's pre_run_cell hook:
import IPython
IPython.get_ipython().events.register('pre_run_cell', configure_plotly_browser_state)

Categories

Resources