Site cannot be reached when graph using plotly

Viewed 1847

I'm trying to use plotly to plot a simple graph

My code is shown as follow

import plotly.express as px

x = [1,2,3]
y = [1,2,3]
fig = px.line(x=x, y=y,labels={'x':x_name,'y':y_name})
fig.show()

when I run this code, sometimes the browser is showing This site can’t be reached

I've searched on this question 1 2 3 , but did not got any answer.

How should I solve this problem when the browser shows This site can’t be reached ?

2 Answers

As you've probably noticed, the site you're trying to reach is localhost (127.0.0.1). Fig.show() creates a server, the browser goes to this server to fetch the image, and the server then shuts down.

If there's a timing (or some other) issue, you'll get the 'site cannot be reached' message.

The issue seems to be in this part of the plotly code:

class OneShotRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

        bufferSize = 1024 * 1024
        for i in range(0, len(html), bufferSize):
            self.wfile.write(html[i : i + bufferSize])

    def log_message(self, format, *args):
        # Silence stderr logging
        pass

server = HTTPServer(("127.0.0.1", 0), OneShotRequestHandler)
webbrowser.get(using).open(
    "http://127.0.0.1:%s" % server.server_port, new=new, autoraise=autoraise
)

server.handle_request()

(see code on GitHub)

My main advice would be to start using Plotly within Jupyter. It works great, and you won't run into this issue.

Related