Home button Search button Dr. Hain buttonClinic website Information for Dizzy Patients Fun Opinions (rants/raves)

Dr. Hain's Rants/Raves has helpful information about things that Dr. Hain has discovered by trial and error.

Plotly javascript Graphics library (This is a qualified rave).

There are many ways to put up graphs on the web. The Plotly library is a very capable method, but it is missing a manual.

The pros and cons of using plotly ?

The google visualization library, is cool when it works, but it doesn't always work. Also, the Google stuff is vulnerable to ... Google. With google, you never know if something is going to vanish tomorrow -- with Plotly, once you "lock down" your library locally, you are probably safe for a long while -- think several years. anyway. Your main vulnerability is browser updates that blow away some part of javascript. Google again with Chrome, and there are always browser upgrades to worry about.

The main problem with plotly is that the learning process is "trial and error". There is no "plotly book". The closest that there seems to be is a python data visualization book. There is an online plotly manual that has 778 pages. It is pretty difficult to navigate 778 pages. Also, what if plotly changes. What there is that is very useful, is a bunch of examples. So you can get up and running, and then try to decrypt the reference manual.

Plotly has three different libraries -- one for javascript (.js), one for python, and one for R. Javascript is much more sensible than python (which requires you to install another program on your computer. We don't use R, so we are not so sure about this, but again, it needs to be installed locally, so it is not really a suitable method of communication with the universe. I am writing here about the javascript version.

Oddly enough, Plotly (which is open source), has a commercial front end. That's OK. But what are they selling ? This is open source right ? It seems as if they are selling support. Perhaps this is the reason that there is no "plotly" book and no "plotly" user manual. Well Ok, thats the way open source sometimes works. We wish them the best.

The plotly people do have some documentation -- it seems to be a work in progress, and it is not really usable.

Still, it is perfectly reasonable to attempt to fix this problem by documenting what one does. In other words, attempt to produce the "missing user manual". We were unable to find anything about how you get php and plotly to cooperate, php is not even mentioned in the "full reference" above, so here is our attempt at this piece of the missing user manual.

How do you use Plotly and PHP together ?

Dr. Hain (author of this page) is very fond of PHP for web pages, especially for pages that use a database (such as mysql), but PHP is a terrible way to produce graphics. First, you really don't want to do lots of processing on your server -- lots of people might be using your server. Javascript, on the other hand, runs locally, is on most browsers (although implementation varies a bit), and also very capable at graphics.

The way to do things then is to use PHP to produce the data that needs to be plotted, perhaps with a database like mysql, put the data into javascript, make a place in html for the graph, and then call the plotly routine to visualize the data.

This process requres you to set up things in html, in javascript and in PHP. This is code that "works", it is not code that is "best practices".

What do you need to do with html to get plotly to work ? Basically, you just create a place holder on your page.

You don't need to do much with html. Just set up a named div, so that you can tell plotly where to draw the graph. The html below sets up a table containing two divs, one named "Result", and one named "Result2".

       	 	<td><div id="Result" style="width: 400px; height: 400px;"></div></td>			<!-- divs for histogram -->
        		<td><div id="Result2" style="width: 400px; height: 400px;"></div></td>			<!-- divs for histogram -->

What do you need to do with javascript to get plotly to work ?

First, you need to load plotly.js library. I do this in the html header.

To avoid awkward surprises when someone updates the library, I do NOT download plotly.js from the most recent distribution, instead I copied the distribution into a local directory on my server, and just use that. In the header, I use:

<script src="plotly-latest.min.js"></script>

Then, one needs to set up the javascript data structures required by plotly. This is the hard part, as the data structures are "documented by example", without a user manual. Perhaps there is some expectation that people will read the open source javascript library.

What you need to do is to implement the following things in javascript:

You also need a plotly graph data structure, which is just a javascript data object. For example, here are two - -one for a bar graph and another for a histogram (see later).

      var instance = {
        type: 'bar',
        name: 'instance'
			// marker: { color:'pink', },			// this will change the color of the bar to pink from the default blue.
var instance2 = { x:[], // y: [], // If you use y rather than x, and also change your php->javascript code, this will make it horizontal. type: 'histogram', name: 'instance2' };

The data within this structure e.g.. instance.x[], are written to by PHP (see later). You can name them whatever you want - -such as "apple" and "oranges" if you prefer.

If you just want to copy a javascript structure, in PHP, this is what you do:

echo "instance2 = JSON.parse(JSON.stringify(instance));\n"; // copy the prototype instance. strange, but this is what it takes.


Second, you need to put the two data strutures into arrays, like below. The array is to allow you to put in two different sources of data, such as instance and instance2, at the same time. You can then stack them or overlay.

plot_data = [instance];
plot_data2 = [instance2];


Thirdly, you need a layout structure.

      var layout = {
        title: plot_title,
        xaxis: {
        	title: 'Bin',
        	autorange: true,
        yaxis: {
	        title: 'Count',
	        autorange: true,

If you add a {barmode: "overlay"} you can overlay two data structures.
If you add a "{barmode: "stack"}  they get stacked.

Finally, you put everything together sticking the plots into the id's named above, using the data as set up, and using whatever layout you prefer.

Plotly.newPlot('Result', plot_data, layout);
Plotly.newPlot('Result2', plot_data2, layout);

Note you need to put the name of the DIV in single quotes. The layout data structure is optional.

What do you need to do with PHP to get plotly to work ?

We will not get very specific here, but in PHP, you need to load in the data and transfer it into javascript. We will assume you are using mysql (which is very standard).

1. Select the database, such as with a command like:

$Mysql = mysql_pconnect($hostname_Mysql, $username_Mysql, $password_Mysql) or trigger_error(mysql_error(),E_USER_ERROR);

2. Query the database, such as with:

$histo = mysql_query($query, $Mysql) or die(mysql_error());

3. Load the results -- there are two ways to do this, I have illustrated a somewhat inefficient method of loading first into PHP, while doing some cleaning, and then into javascript.

Load into a php array, such as with:

while($row = mysql_fetch_row($histo)) {
   $value = $row[0];
   $value=trim($value);			// get rid of leading and trailing white space
   $hdata[] = $value;

Load the php data into into javascript, such as with another php loop. This is an example for the instance2, but one also would need to do the instance data, to get this to work.

 for($i=1; $i<count($hdata); $i++) { 
	printf("instance2.x[%d]=%d;\n", $i, $hdata[$i]); 

One could certainly do both of these at the same time -- i.e. just load the data and put it into javascript

Plotly methods of doing things.

Once you get the general idea of putting data into javascript, and setting up the data structures, the BIG PROBLEM with plotly is figuring out what goes into the data structures, because this conditions the behavior of the plotly program that puts up your graph. Here we have extracted a few options from the examples.


See this page for examples from the plotly people.


The example code above produces the following plots:

On the left is a bar graph using the data in "instance". On the right is a "histogram", using the data in instance 2.

For the bar graph on the left, we had to supply both X and Y, and call an analysis routine that computed the # of X values in each Bin. For the histogram, plotly just needs a set of values, and it automatically assorts it into bins. It has the same raw data values, but the bins are chosen by Plotly rather than set up in the bar graph code. So the histogram needs much less processing in PHP, and also less knowledge about the data, which is very good.

Note that the type of graph you get, histogram here, is controlled by the "type" field in the data structure ! It is not controlled by a field within the layout structure.

The binning option can be turned off, with autobinx: false,. Then you need to set up your own bins such as with xbins: { end: 4, size: 0.06, start: -3.2 } . So one could probably reproduce the graph on the left, on the right, by setting the bins up yourself.

You can do a cumulative histogram using the syntax:

type: 'histogram',

cumulative: {enabled: true}


You can also do stacked bar graphs, by providing two different sources of data.




© Copyright March 4, 2018 , Timothy C. Hain, M.D. All rights reserved.
Dr Hain's CV Clinic dizziness-and-hearing.com FLW Rant-Rave