Retro Gamer
Retro Gamer

Reputation: 1112

Why am I getting an Uncaught ReferenceError: Plotly is not defined

I am getting an Uncaught ReferenceError: Plotly is not defined error when my page loads. The following code is beneath my div element where the plot is rendered, but on the line Plotly.newPlot('myDiv', dataPlot, layout); within the socket.on listener is where this error is being thrown.

var dataPlot = [{
    x: ['a', 'b', 'c', 'd'],
    y: [0, 0, 0, 0],
    type: 'bar'
}];

var layout = {
    autosize: false,
    width: 500,
    height: 500,
    margin: {
        l: 50,
        r: 50,
        b: 100,
        t: 100,
        pad: 4
    }
};

// Listener, whenever the server emits 'updatechat', this updates the chat body
socket.on('updatechat', function (username, data) {
    $('#conversation').append('<b>'+username + ':</b> ' + data + '<br>');
    if (data ==='a'){
        dataPlot[0]['y'][0]++;
    } else if (data === 'b'){
        dataPlot[0]['y'][1]++;
    } else if (data === 'c'){
        dataPlot[0]['y'][2]++;
    } else if (data === 'd'){
        dataPlot[0]['y'][3]++;
    }
    Plotly.newPlot('myDiv', dataPlot, layout);
});

$("#clearplot").click(function() {
    var dataPlot = [{
    x: ['a', 'b', 'c', 'd'],
    y: [0, 0, 0, 0],
    type: 'bar'
    }]
    Plotly.newPlot('myDiv', dataPlot, layout);
});

I have included <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> in the head of my HTML5 document, and the Plotly.newPlot('myDiv', dataPlot, layout); within my clearplot function is working just fine. Why is there an error only in the updatechat listener?

EDIT I figured out the issue. The issue was that this code is embedded in an Angular app, so I just had to include the <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> within the head of the template HTML file, not the local HTML file.

Upvotes: 14

Views: 22349

Answers (2)

Jorge Guerra Pires
Jorge Guerra Pires

Reputation: 632

I had the same problem, but I have used the wrong script. It took me some minutes and patience to found out.

Just to maybe help somebody else:

I was using:

src="plotly-2.12.1.min.js"

Should use:

src="https://cdn.plot.ly/plotly-2.12.1.min.js"

For new ones to Angular: it is the same trick of Boostrap, you either import from a link or download the whole package, and place it locally on Assets. I wanted to use the package without downloading, but calling locally, generally in Assets of Angular app folder. 😎😄

Documentation here

Upvotes: 1

Or Assayag
Or Assayag

Reputation: 6336

Looks like you forgot to include Plotly script reference to your code.
Try to add:
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
In the <head> section of your HTML page.

Upvotes: 8

Related Questions