- Undocumented Matlab - https://undocumentedmatlab.com -

Plotly graphs in IPython Notebook

Posted By Yair Altman On May 14, 2014 | 1 Comment

Last December, I hosted an article on plot.ly [1]‘s awesome online plotting interface for Matlab. Today, I wish to welcome Andrey Dimitrov, a plot.ly engineer, who will discuss generating Plotly graphs in IPython Notebooks, all from within Matlab. The Plotly idea, of generating online interactive graphs, is radically different from Matlab’s standard static plots and deserves a second look. Note that Plotly is a commercial venture.


The Plotly Matlab API [2] enables leveraging the power of Plotly graphs conveniently from your Matlab environment, meaning that you can make a graph like this in Matlab:

You can work in Matlab, share your graphs and data, and then edit it together online. It’s all backed up, collaborative, and can be edited with other APIs and the GUI. It’s free, embeddable, and keeps data and graphs together.
The API provides a set of functions that structure your data and send it to Plotly. All editing can be done through the API or the online GUI. In addition, the Plotly wrapper function can take away all the hassle of learning a new graphing syntax. Just build your figures in Matlab as usual and send them to Plotly with one call to the wrapper.
This notebook goes through some usage scenarios to get Matlab users started with the tool. A version of this post (with several more examples) was also written as an IPython Notebook [3]. Some steps are specific to making everything work in an IPython notebook, but you can always skip through those and get to the good stuff.

A simple example

First, we need to start a Matlab server. In the IPython Notebook:

In [1]:
import pymatbridge as pymat
ip = get_ipython()
pymat.load_ipython_extension(ip, matlab='C:\Users\Andrey\matlab_shortcut.lnk')

This starts Matlab on the local computer and we can now enter Matlab commands in our IPython Notebook:

Starting Matlab on http://localhost:60199
 visit http://localhost:60199/exit.m to shut down same
...Matlab started and connected!

Note to Windows users: Python doesn’t like file paths with spaces! Above, a shortcut to matlab.exe was created and placed it in a path that did not contain spaces. It’s a bit of a hack, there are better ways to do it I’m sure.
Now we are ready to run Matlab. Let’s set up the Plotly environment next. This needs to be done only once per session. The next few lines import the Plotly Matlab API and sign in to your account. For these examples we are using the Matlab-demos account. You can sign up at Plotly [4] to get a username and key (more info [5]), or just use the Matlab-demos username and key below to make these examples work. In Matlab:

In [2]:
api_path = 'C:\Users\Andrey\Dropbox\ANDREY\PLOTLY\Matlab-api\plotly';
signin('Matlab-demos', '3qhoowzv5n');  % account username & key

We are now signed in and can convert and publish the Matlab figures in Plotly. The Plotly Matlab API helps generate data and layout data structures that contain all the information needed to make a plot. The plotly command sends these to the server and the result is displayed via the response variable. In it, a URL points to the generated plot online. In this notebook, we focus of the Plotly wrapper. The fig2plotly command at the end of the code will convert the current figure into a format that Plotly understands and publish it.
Let’s make a simple plot in Matlab and publish it to Plotly:

In [3]:
% some random points
my_random_data = rand(20,4);
% a 2D scatter plot with size and color inputs
scatter(my_random_data(:,1), my_random_data(:,2), 100*my_random_data(:,3), my_random_data(:,4), 'filled')
% Convert the static figure into an online Plotly chart
response = fig2plotly();
High five! You successfully sent some data to your account on Plotly. View your plot in your browser at https://plot.ly/~Matlab-demos/0 or inside your plot.ly account where it is named 'untitled'.

The plot has been sent to the Matlab-demos account and the command returns the unique URL https://plot.ly/~Matlab-demos/0 [6] where anyone can view the rendered graph. By default, the plot is named “untitled”. In the following examples, we see how the command allows the user to give a custom name, otherwise it will try to extract it from the figure title.
Every plotly graph URL can be embedded in HTML as wrapped in an IFrame [7]. In fact, the Plotly figure above can be embedded in an HTML (as in this webpage) using the following HTML code:

Here’s a quick Python utility function that will embed a plotly graph in IPython Notebooks:

In [4]:
from IPython.display import HTML
def show_plot(url, width=700, height=500):
    s = '' %\
    (height+50, "/".join(map(str,[url, width, height])), width+50)
    return HTML(s)

To see the resulting plot, we only need to input the following command:

In [5]:

(resulting in a display of the interactive chart above)

Example 2: Convex Hull

Note: The original example data can be found at the Matlab Plot Gallery [8].

In [6]:
% This is an example of how to add text to a plot in Matlab.
% Read about the  function in the Matlab documentation.
% Go to 
% Load the points for creating a spline curve
% Plot the points for the spline curve
plot(points(:,1), points(:,2), ':ok');
hold on;
% Plot the spline curve
plot(x, y, 'LineWidth', 2);
axis([0.5 7 -0.8 1.8]);
% Add a title and axis labels
title('The Convex-Hull Property');
% Label points 3, 4, & 5 of the spline curve
xt = points(3,1) - 0.05;
yt = points(3,2) - 0.10;
text(xt, yt, 'Point 3', 'FontSize',12);
xt = points(4,1) - 0.05;
yt = points(4,2) + 0.10;
text(xt, yt, 'Point 4', 'FontSize',12);
xt = points(5,1) + 0.15;
yt = points(5,2) - 0.05;
text(6.1,.5, 'Point 5', 'FontSize',12);
% Convert the static figure into an online Plotly chart
response = fig2plotly();

This time, the plot was named “The Convex Hull Property”. Back in the IPython Notebook:

In [7]:
Out [7]:

Sweet! Let’s keep going…
We will reuse the same code and add some more inputs to the fig2plotly command. We can specify explicitly the figure object that will be published (it doesn’t need to be the current one). In addition, we add ‘open’ to turn off the automatic opening of a browser window with the response URL, and we ‘strip’ the plot of all Matlab styling and revert to Plotly defaults. This allows users to use Plotly’s styling capabilities from the API of at the online UI.
The Matlab code is as above, except for the last (fig2plotly) line:

% Convert the static figure into an online Plotly chart
hFig = gcf;  % any figure, for now we use the current
response = fig2plotly(hFig, 'strip',true, 'open',false, 'name','Stripped plot');
In [8]:
Out [8]:

Example 3: Multiple Plots

In [9]:
% Create data
t = linspace(0,2*pi);
t(1) = eps;
y = sin(t);
% Place axes at (0.1,0.1) with width and height of 0.8
handaxes1 = axes('position', [0.1 0.1 0.8 0.8]);
% Main plot
plot(t, y);
set(handaxes1, 'box', 'off');
% Adjust X/Y label font
set(get(gca, 'xlabel'), 'fontsize',16, 'fontweight','bold');
set(get(gca, 'ylabel'), 'fontsize',16, 'fontweight','bold');
% Place second set of axes on same plot
handaxes2 = axes('position', [0.6 0.6 0.2 0.2]);
fill(t, y.^2, 'g');
set(handaxes2, 'box', 'off');
% Adjust X/Y label font
set(get(handaxes2,'xlabel'), 'fontname','times')
set(get(handaxes2,'ylabel'), 'fontname','times')
% Add another set of axes
handaxes3 = axes('position', [0.25 0.25 0.2 0.2]);
plot(t, y.^3);
set(handaxes3, 'box','off');
% Convert the static figure into an online Plotly chart
response = fig2plotly(gcf, 'name','Multiple_Plots');
In [10]:
Out [10]:

Check out more examples interactive Plotly and Matlab graphs in IPython notebooks here [9].

Categories: Guest bloggers, GUI, Low risk of breaking in future versions

1 Comment (Open | Close)

1 Comment To "Plotly graphs in IPython Notebook"

#1 Comment By Oleg Komarov On May 14, 2014 @ 13:34

There’s a submission with the Matlab API on the FEX: [16]
The submission can now be linked to github and it would be great if it was done.

Article printed from Undocumented Matlab: https://undocumentedmatlab.com

URL to article: https://undocumentedmatlab.com/articles/plotly-graphs-in-ipython-notebook

URLs in this post:

[1] plot.ly: http://plot.ly

[2] Plotly Matlab API: https://plot.ly/api/MATLAB

[3] IPython Notebook: http://nbviewer.ipython.org/github/plotly/IPython-plotly/blob/master/See more/MATLAB_Wrapper_Examples.ipynb

[4] sign up at Plotly: https://plot.ly/ssi/

[5] more info: https://plot.ly/api/MATLAB/getting-started/authentication

[6] https://plot.ly/~Matlab-demos/0: https://plot.ly/~Matlab-demos/0

[7] embedded in HTML as wrapped in an IFrame: https://plot.ly/api/MATLAB/docs/iframes

[8] Matlab Plot Gallery: http://www.mathworks.com/discovery/gallery.html

[9] here: http://nbviewer.ipython.org/github/plotly/IPython-plotly/tree/master/

[10] Plotly graphs : https://undocumentedmatlab.com/articles/plotly-graphs

[11] JFreeChart graphs and gauges : https://undocumentedmatlab.com/articles/jfreechart-graphs-and-gauges

[12] Pinning annotations to graphs : https://undocumentedmatlab.com/articles/pinning-annotations-to-graphs

[13] Customizing axes part 5 – origin crossover and labels : https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels

[14] Plot performance : https://undocumentedmatlab.com/articles/plot-performance

[15] Accessing plot brushed data : https://undocumentedmatlab.com/articles/accessing-plot-brushed-data

[16] : http://www.mathworks.co.uk/matlabcentral/fileexchange/42202-plotly-api

Copyright © Yair Altman - Undocumented Matlab. All rights reserved.