Undocumented Matlab
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT

Plotly graphs in IPython Notebook

May 14, 2014 One Comment

Last December, I hosted an article on plot.ly‘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.

Overview

The Plotly Matlab API 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. 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')

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 to get a username and key (more info), or just use the Matlab-demos username and key below to make these examples work. In Matlab:

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

In [2]: %%matlab api_path = 'C:\Users\Andrey\Dropbox\ANDREY\PLOTLY\Matlab-api\plotly'; addpath(genpath(api_path)) 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
figure
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'.

In [3]: % some random points my_random_data = rand(20,4); % a 2D scatter plot with size and color inputs figure 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 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. In fact, the Plotly figure above can be embedded in an HTML (as in this webpage) using the following HTML code:

<iframe src="https://plot.ly/~Matlab-demos/0/400/320/" width="400" height="320" seamless="seamless" scrolling="no"></iframe>

<iframe src="https://plot.ly/~Matlab-demos/0/400/320/" width="400" height="320" seamless="seamless" scrolling="no"></iframe>


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 = '<iframe height="%s" id="igraph" scrolling="no" seamless="seamless" src="%s" width="%s"></iframe>' %\
    (height+50, "/".join(map(str,[url, width, height])), width+50)
    return HTML(s)

In [4]: from IPython.display import HTML def show_plot(url, width=700, height=500): s = '<iframe height="%s" id="igraph" scrolling="no" seamless="seamless" src="%s" width="%s"></iframe>' %\ (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]:
show_plot('https://plot.ly/~Matlab-demos/0')

In [5]: show_plot('https://plot.ly/~Matlab-demos/0')

(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.

In [6]:
%%matlab
% This is an example of how to add text to a plot in Matlab.
% Read about the <http://www.mathworks.com/help/matlab/ref/text.html |text|> function in the Matlab documentation.
% Go to <http://www.mathworks.com/discovery/gallery.html Matlab Plot Gallery>
% Load the points for creating a spline curve
load('C:\Users\Andrey\Dropbox\ANDREY\PLOTLY\Matlab_Examples\Add_Text_to_Plot_1\splineData');
% Plot the points for the spline curve
figure;
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');
xlabel('x');
ylabel('y');
% 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();

In [6]: %%matlab % This is an example of how to add text to a plot in Matlab. % Read about the <http://www.mathworks.com/help/matlab/ref/text.html |text|> function in the Matlab documentation. % Go to <http://www.mathworks.com/discovery/gallery.html Matlab Plot Gallery> % Load the points for creating a spline curve load('C:\Users\Andrey\Dropbox\ANDREY\PLOTLY\Matlab_Examples\Add_Text_to_Plot_1\splineData'); % Plot the points for the spline curve figure; 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'); xlabel('x'); ylabel('y'); % 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]:
show_plot('https://plot.ly/~Matlab-demos/1')
Out [7]:

In [7]: show_plot('https://plot.ly/~Matlab-demos/1') 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');

% 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]:
show_plot('https://plot.ly/~Matlab-demos/2')
Out [8]:

In [8]: show_plot('https://plot.ly/~Matlab-demos/2') Out [8]:

Example 3: Multiple Plots

In [9]:
%%matlab
% 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
figure;
handaxes1 = axes('position', [0.1 0.1 0.8 0.8]);
% Main plot
plot(t, y);
xlabel('t');
ylabel('sin(t)');
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');
xlabel('t');
ylabel('(sin(t))^2');
% 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');
xlabel('t');
ylabel('(sin(t))^3');
% Convert the static figure into an online Plotly chart
response = fig2plotly(gcf, 'name','Multiple_Plots');

In [9]: %%matlab % 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 figure; handaxes1 = axes('position', [0.1 0.1 0.8 0.8]); % Main plot plot(t, y); xlabel('t'); ylabel('sin(t)'); 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'); xlabel('t'); ylabel('(sin(t))^2'); % 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'); xlabel('t'); ylabel('(sin(t))^3'); % Convert the static figure into an online Plotly chart response = fig2plotly(gcf, 'name','Multiple_Plots');

In [10]:
show_plot('https://plot.ly/~Matlab-demos/3')
Out [10]:

In [10]: show_plot('https://plot.ly/~Matlab-demos/3') Out [10]:


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

Related posts:

  1. Plotly graphs – Plotly charts can be created and customized in Matlab. ...
  2. JFreeChart graphs and gauges – JFreeChart is an open-source charting library that can easily be integrated in Matlab...
  3. Pinning annotations to graphs – Annotation object can be programmatically set at, and pinned-to, plot axes data points. ...
  4. Customizing axes part 5 – origin crossover and labels – The axes rulers (axles) can be made to cross-over at any x,y location within the chart. ...
  5. Plot performance – Undocumented inner plot mechanisms can significantly improve plotting performance ...
  6. Accessing plot brushed data – Plot data brushing can be accessed programmatically using very simple pure-Matlab code...
Commercial Plotly
Print Print
« Previous
Next »
One Response
  1. Oleg Komarov May 14, 2014 at 13:34 Reply

    There’s a submission with the Matlab API on the FEX: http://www.mathworks.co.uk/matlabcentral/fileexchange/42202-plotly-api
    The submission can now be linked to github and it would be great if it was done.

Leave a Reply
HTML tags such as <b> or <i> are accepted.
Wrap code fragments inside <pre lang="matlab"> tags, like this:
<pre lang="matlab">
a = magic(3);
disp(sum(a))
</pre>
I reserve the right to edit/delete comments (read the site policies).
Not all comments will be answered. You can always email me (altmany at gmail) for private consulting.

Click here to cancel reply.

Useful links
  •  Email Yair Altman
  •  Subscribe to new posts (feed)
  •  Subscribe to new posts (reader)
  •  Subscribe to comments (feed)
 
Accelerating MATLAB Performance book
Recent Posts

Speeding-up builtin Matlab functions – part 3

Improving graphics interactivity

Interesting Matlab puzzle – analysis

Interesting Matlab puzzle

Undocumented plot marker types

Matlab toolstrip – part 9 (popup figures)

Matlab toolstrip – part 8 (galleries)

Matlab toolstrip – part 7 (selection controls)

Matlab toolstrip – part 6 (complex controls)

Matlab toolstrip – part 5 (icons)

Matlab toolstrip – part 4 (control customization)

Reverting axes controls in figure toolbar

Matlab toolstrip – part 3 (basic customization)

Matlab toolstrip – part 2 (ToolGroup App)

Matlab toolstrip – part 1

Categories
  • Desktop (45)
  • Figure window (59)
  • Guest bloggers (65)
  • GUI (165)
  • Handle graphics (84)
  • Hidden property (42)
  • Icons (15)
  • Java (174)
  • Listeners (22)
  • Memory (16)
  • Mex (13)
  • Presumed future risk (394)
    • High risk of breaking in future versions (100)
    • Low risk of breaking in future versions (160)
    • Medium risk of breaking in future versions (136)
  • Public presentation (6)
  • Semi-documented feature (10)
  • Semi-documented function (35)
  • Stock Matlab function (140)
  • Toolbox (10)
  • UI controls (52)
  • Uncategorized (13)
  • Undocumented feature (217)
  • Undocumented function (37)
Tags
AppDesigner (9) Callbacks (31) Compiler (10) Desktop (38) Donn Shull (10) Editor (8) Figure (19) FindJObj (27) GUI (141) GUIDE (8) Handle graphics (78) HG2 (34) Hidden property (51) HTML (26) Icons (9) Internal component (39) Java (178) JavaFrame (20) JIDE (19) JMI (8) Listener (17) Malcolm Lidierth (8) MCOS (11) Memory (13) Menubar (9) Mex (14) Optical illusion (11) Performance (78) Profiler (9) Pure Matlab (187) schema (7) schema.class (8) schema.prop (18) Semi-documented feature (6) Semi-documented function (33) Toolbar (14) Toolstrip (13) uicontrol (37) uifigure (8) UIInspect (12) uitable (6) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
Contact us
Captcha image for Custom Contact Forms plugin. You must type the numbers shown in the image
Undocumented Matlab © 2009 - Yair Altman
This website and Octahedron Ltd. are not affiliated with The MathWorks Inc.; MATLAB® is a registered trademark of The MathWorks Inc.
Scroll to top