简体   繁体   English

使用 Kaleido 导出 Plotly 图表不起作用?

[英]Exporting Plotly charts with Kaleido not working?

I have locally created plotly charts in Jupyter Notebook that I'm trying to save as png files on my local machine.我在 Jupyter Notebook 中本地创建了 plotly 图表,我试图在本地机器上保存为 png 文件。 Example of charts:图表示例:

for table in EG_SD_pivots:
    df = EG_SD_pivots[table].reset_index()
    fig = make_subplots(specs=[[{"secondary_y": True}]])

    fig.add_trace(
            go.Scatter(x=df.iloc[:, 0], y=df['SD_Credibility'], name="Credibility", marker=dict(color=yellow)), secondary_y=True)

    fig.add_trace(
            go.Bar(x=df.iloc[:, 0], y=df['EG_LR_Rel'], name="EG Relativity", marker=dict(color=teal)), secondary_y=False)

    fig.add_trace(
            go.Bar(x=df.iloc[: ,0], y=df['SD_LR_Rel'], name="SD Relativity", marker=dict(color=indigo)), secondary_y=False)

    # Add figure title
    fig.update_layout(title_text=df.iloc[:0].columns[0], margin=dict(b=200))

    # Set x-axis title
    fig.update_xaxes(title_text=df.iloc[:0].columns[0])

    fig.update_yaxes(title_text="<b>Relativity</b>", secondary_y=False)
    fig.update_yaxes(title_text="<b>Credibility</b>", secondary_y=True)
    fig.show()

I've tried a number of different solutions, but they've all returned various errors... Solutions: fig.to_image(format="png") --> returns我尝试了许多不同的解决方案,但它们都返回了各种错误...解决方案: fig.to_image(format="png") --> 返回

ValueError: 
The orca executable is required to export figures as static images,
but it could not be found on the system path.

plotly.orca.config.executable = 'C:/Program Files/Anaconda3/pkgs/plotly-4.0.0-py_0/site-packages/plotly/io/_orca.py' --> returns plotly.orca.config.executable = 'C:/Program Files/Anaconda3/pkgs/plotly-4.0.0-py_0/site-packages/plotly/io/_orca.py' --> 返回

AttributeError: module 'chart_studio.plotly' has no attribute 'orca'

plotly.offline.iplot(fig, filename=(str(chart) + '.png')) --> returns plotly.offline.iplot(fig, filename=(str(chart) + '.png')) --> 返回

AttributeError: module 'chart_studio.plotly' has no attribute 'offline'

fig.write_image("EG_SD_images/" + str(chart) + ".png", engine="kaleido") --> returns fig.write_image("EG_SD_images/" + str(chart) + ".png", engine="kaleido") --> 返回

`TypeError: write_image() got an unexpected keyword argument 'engine'`

plotly.image.save_as(fig, filename=(str(chart) + '.png')) --> returns plotly.image.save_as(fig, filename=(str(chart) + '.png')) --> 返回

Error                                     Traceback (most recent call last)
C:\Program Files\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname)
    452             try:
--> 453                 cnx.do_handshake()
    454             except OpenSSL.SSL.WantReadError:

C:\Program Files\Anaconda3\lib\site-packages\OpenSSL\SSL.py in do_handshake(self)
   1906         result = _lib.SSL_do_handshake(self._ssl)
-> 1907         self._raise_ssl_error(self._ssl, result)
   1908 

C:\Program Files\Anaconda3\lib\site-packages\OpenSSL\SSL.py in _raise_ssl_error(self, ssl, result)
   1638         else:
-> 1639             _raise_current_error()
   1640 

C:\Program Files\Anaconda3\lib\site-packages\OpenSSL\_util.py in exception_from_error_queue(exception_type)
     53 
---> 54     raise exception_type(errors)
     55 

Error: [('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')]

During handling of the above exception, another exception occurred:

SSLError                                  Traceback (most recent call last)
C:\Program Files\Anaconda3\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    599                                                   body=body, headers=headers,
--> 600                                                   chunked=chunked)
    601 

C:\Program Files\Anaconda3\lib\site-packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    342         try:
--> 343             self._validate_conn(conn)
    344         except (SocketTimeout, BaseSSLError) as e:

C:\Program Files\Anaconda3\lib\site-packages\urllib3\connectionpool.py in _validate_conn(self, conn)
    838         if not getattr(conn, 'sock', None):  # AppEngine might not have  `.sock`
--> 839             conn.connect()
    840 

C:\Program Files\Anaconda3\lib\site-packages\urllib3\connection.py in connect(self)
    343             server_hostname=server_hostname,
--> 344             ssl_context=context)
    345 

C:\Program Files\Anaconda3\lib\site-packages\urllib3\util\ssl_.py in ssl_wrap_socket(sock, keyfile, certfile, cert_reqs, ca_certs, server_hostname, ssl_version, ciphers, ssl_context, ca_cert_dir)
    343         if HAS_SNI and server_hostname is not None:
--> 344             return context.wrap_socket(sock, server_hostname=server_hostname)
    345 

C:\Program Files\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname)
    458             except OpenSSL.SSL.Error as e:
--> 459                 raise ssl.SSLError('bad handshake: %r' % e)
    460             break

SSLError: ("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])",)

During handling of the above exception, another exception occurred:

MaxRetryError                             Traceback (most recent call last)
C:\Program Files\Anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    448                     retries=self.max_retries,
--> 449                     timeout=timeout
    450                 )

C:\Program Files\Anaconda3\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    637             retries = retries.increment(method, url, error=e, _pool=self,
--> 638                                         _stacktrace=sys.exc_info()[2])
    639             retries.sleep()

C:\Program Files\Anaconda3\lib\site-packages\urllib3\util\retry.py in increment(self, method, url, response, error, _pool, _stacktrace)
    397         if new_retry.is_exhausted():
--> 398             raise MaxRetryError(_pool, url, error or ResponseError(cause))
    399 

MaxRetryError: HTTPSConnectionPool(host='api.plotly.com', port=443): Max retries exceeded with url: /v2/images (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])")))

During handling of the above exception, another exception occurred:

SSLError                                  Traceback (most recent call last)
C:\Program Files\Anaconda3\lib\site-packages\chart_studio\api\v2\utils.py in request(method, url, **kwargs)
    171     try:
--> 172         response = requests.request(method, url, **kwargs)
    173     except RequestException as e:

C:\Program Files\Anaconda3\lib\site-packages\requests\api.py in request(method, url, **kwargs)
     59     with sessions.Session() as session:
---> 60         return session.request(method=method, url=url, **kwargs)
     61 

C:\Program Files\Anaconda3\lib\site-packages\requests\sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    532         send_kwargs.update(settings)
--> 533         resp = self.send(prep, **send_kwargs)
    534 

C:\Program Files\Anaconda3\lib\site-packages\requests\sessions.py in send(self, request, **kwargs)
    645         # Send the request
--> 646         r = adapter.send(request, **kwargs)
    647 

C:\Program Files\Anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    513                 # This branch is for urllib3 v1.22 and later.
--> 514                 raise SSLError(e, request=request)
    515 

SSLError: HTTPSConnectionPool(host='api.plotly.com', port=443): Max retries exceeded with url: /v2/images (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])")))

During handling of the above exception, another exception occurred:

PlotlyRequestError                        Traceback (most recent call last)
<ipython-input-39-fb5a62f7ab75> in <module>
     69     fig.show()
     70     EG_SD_charts[table] = fig
---> 71     plotly.image.save_as(fig, filename=(str(chart) + '.png'))
     72     #plotly.offline.iplot(fig, filename=(str(chart) + '.png'))
     73     #fig.write_image("EG_SD_images/" + str(chart) + ".png", engine="kaleido")

C:\Program Files\Anaconda3\lib\site-packages\chart_studio\plotly\plotly.py in save_as(cls, figure_or_data, filename, format, width, height, scale)
    908             filename += "." + format
    909 
--> 910         img = cls.get(figure_or_data, format, width, height, scale)
    911 
    912         f = open(filename, "wb")

C:\Program Files\Anaconda3\lib\site-packages\chart_studio\plotly\plotly.py in get(figure_or_data, format, width, height, scale)
    817             payload["scale"] = scale
    818 
--> 819         response = v2.images.create(payload)
    820 
    821         headers = response.headers

C:\Program Files\Anaconda3\lib\site-packages\chart_studio\api\v2\images.py in create(body)
     16     """
     17     url = build_url(RESOURCE)
---> 18     return request("post", url, json=body)

C:\Program Files\Anaconda3\lib\site-packages\retrying.py in wrapped_f(*args, **kw)
     47             @six.wraps(f)
     48             def wrapped_f(*args, **kw):
---> 49                 return Retrying(*dargs, **dkw).call(f, *args, **kw)
     50 
     51             return wrapped_f

C:\Program Files\Anaconda3\lib\site-packages\retrying.py in call(self, fn, *args, **kwargs)
    204 
    205             if not self.should_reject(attempt):
--> 206                 return attempt.get(self._wrap_exception)
    207 
    208             delay_since_first_attempt_ms = int(round(time.time() * 1000)) - start_time

C:\Program Files\Anaconda3\lib\site-packages\retrying.py in get(self, wrap_exception)
    245                 raise RetryError(self)
    246             else:
--> 247                 six.reraise(self.value[0], self.value[1], self.value[2])
    248         else:
    249             return self.value

C:\Program Files\Anaconda3\lib\site-packages\six.py in reraise(tp, value, tb)
    691             if value.__traceback__ is not tb:
    692                 raise value.with_traceback(tb)
--> 693             raise value
    694         finally:
    695             value = None

C:\Program Files\Anaconda3\lib\site-packages\retrying.py in call(self, fn, *args, **kwargs)
    198         while True:
    199             try:
--> 200                 attempt = Attempt(fn(*args, **kwargs), attempt_number, False)
    201             except:
    202                 tb = sys.exc_info()

C:\Program Files\Anaconda3\lib\site-packages\chart_studio\api\v2\utils.py in request(method, url, **kwargs)
    177         status_code = response.status_code if response else None
    178         content = response.content if response else "No content"
--> 179         raise exceptions.PlotlyRequestError(message, status_code, content)
    180     validate_response(response)
    181     return response

PlotlyRequestError: No message

I also had the error: TypeError: write_image() got an unexpected keyword argument 'engine'.我也遇到了错误: TypeError: write_image() got an unexpected keyword argument 'engine'. According to plotly/Kaleido manual :根据情节/万花筒手册

Versions 4.9 and above of the Plotly Python library will automatically use Kaleido for static image export when Kaleido is installed. Plotly Python 库的 4.9 及更高版本将在安装 Kaleido 时自动使用 Kaleido 进行 static 图像导出。

Try to check the version by:尝试通过以下方式检查版本:

 import plotly plotly.__version__

You can then update your Plotly by:然后,您可以通过以下方式更新您的 Plotly:

 pip install plotly==5.3.1

This will uninstall the old version and install the recent one.这将卸载旧版本并安装最新版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM