Как использовать plot.ly в режиме free / opensource - PullRequest
0 голосов
/ 23 ноября 2018

С сайта plot.ly для histogram https://plot.ly/python/histograms/ у нас есть следующий фрагмент:

import plotly.plotly as py
import plotly.graph_objs as go

import numpy as np
x = np.random.randn(500)
data = [go.Histogram(x=x)]
py.iplot(data, filename='basic histogram')

Но выполнение этого дает нам жалобы, что оно не запускается на их размещенной службе:

Aw, snap! We didn't get a username with your request.

Don't have an account? https://plot.ly/api_signup

Questions? accounts@plot.ly
---------------------------------------------------------------------------
PlotlyError                               Traceback (most recent call last)
<ipython-input-33-bf076fa5dd12> in <module>
      7 data = [go.Histogram(x=x)]
      8
----> 9 py.iplot(data, filename='basic histogram')

~/Library/Python/3.6/lib/python/site-packages/plotly/plotly/plotly.py in iplot(figure_or_data, **plot_options)
    162         embed_options['height'] = str(embed_options['height']) + 'px'
    163
--> 164     return tools.embed(url, **embed_options)
    165
    166

~/Library/Python/3.6/lib/python/site-packages/plotly/tools.py in embed(file_owner_or_url, file_id, width, height)
    394         else:
    395             url = file_owner_or_url
--> 396         return PlotlyDisplay(url, width, height)
    397     else:
    398         if (get_config_defaults()['plotly_domain']

~/Library/Python/3.6/lib/python/site-packages/plotly/tools.py in __init__(self, url, width, height)
   1438         def __init__(self, url, width, height):
   1439             self.resource = url
-> 1440             self.embed_code = get_embed(url, width=width, height=height)
   1441             super(PlotlyDisplay, self).__init__(data=self.embed_code)
   1442

~/Library/Python/3.6/lib/python/site-packages/plotly/tools.py in get_embed(file_owner_or_url, file_id, width, height)
    299                 "'{1}'."
    300                 "\nRun help on this function for more information."
--> 301                 "".format(url, plotly_rest_url))
    302         urlsplit = six.moves.urllib.parse.urlparse(url)
    303         file_owner = urlsplit.path.split('/')[1].split('~')[1]

PlotlyError: Because you didn't supply a 'file_id' in the call, we're assuming you're trying to snag a figure from a url. You supplied the url, '', we expected it to start with 'https://plot.ly'.
Run help on this function for more information.

In [34]: 2018-11-22 17:40:38.622 Python[26768:4641247] Persistent UI failed to open file file:///Users/sboesch/Library/Saved%20Application%20State/org.python.python.savedState/window_1.data: No such file or directory (2)

Так как же использовать plot.ly из стандартного ipython REPL?

Ответы [ 2 ]

0 голосов
/ 23 ноября 2018

Начиная с сюжета 3, вы можете работать в Jupyter Notebooks, используя только plotly.graph_objs, хотя FigureWidget, если вам нужно явно показать график, вы можете использовать display ipython, как и с любым другим виджетом:

from IPython import display
from plotly import graph_objs as go    
import numpy as np

x = np.random.randn(500)
figure = go.FigureWidget()
figure.add_trace(go.Histogram(x=x))
display.display(figure)
0 голосов
/ 23 ноября 2018

Требуются две вещи: во-первых, , убедитесь, что у вас установлена ​​последняя версия plotly: у меня была 1.8.3, и после обновления до 2.7.0 все выглядит намного лучше.

Кроме того: из комментария @cody - я более внимательно посмотрел на режим offline на http: // plot.ly/python/offline.Не сразу видно, какой способ построения: но нам нужно запустить следующую магию:

init_notebook_mode(connected=True)

Итак, фрагмент кода теперь:

from plotly import __version__
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd
import requests
bike = pd.read_json('/shared/bikeRental.json',lines=True)
#bike.createOrReplaceTempView('bike')
#x=sqldf('select Duration from bikePd where Duration < 7200')
x=sqldf('select Duration from bike where Duration < 7200')
init_notebook_mode(connected=True)
hist = [go.Histogram(x=x['Duration'].values)]
plot(hist,filename='/shared/bikeRides')

, который производит:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...