Running MATLAB in an IPython Notebook

With Interactive MATLAB Graphing in Plotly

Check out more examples interactive Plotly graphs in IPython notebooks here: nbviewer.ipython.org/github/plotly/IPython-plotly/tree/master/

Questions? andrey@plot.ly, @plotlygraphs

The following is a list of usage examples of Plotly in Matlab. The original example data can be found at the Matlab Plot Gallery

First, we need to start a MATLAB server:


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


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

Note to Windows users: Python doesn't like file paths with spaces! Above, I created a shortcut to matlab.exe and placed it in 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! The following code segments follow the same genearal structure: connect to Plotly, generate the necessary data structures, and send the graph request. The response is the url where the plot is located.

EXAMPLE 1: Morse Signal Analysis


In [3]:
%%matlab
% set up plotly environment
clear all

api_path = 'C:\Users\Andrey\Dropbox\ANDREY\PLOTLY\API_matlab\plotly';
addpath(genpath(api_path))
signin('andreyDim', 'r0x3w3ivg4');

% Load Morse data
load 'C:\Users\Andrey\Dropbox\ANDREY\PLOTLY\Matlab_Examples\Line_Plot_2D_3\MDdata'

% specify the style of each trace
data1 = struct(...
  'x', dissimilarities, ...
  'y', dist1, ...
  'type', 'scatter', ...
  'name', 'Stress', ...
  'mode', 'markers', ...
  'marker', struct('opacity', 0.5, ...
    'symbol','triangle-up', ... 
    'size',8, ...
    'color', 'rgb(54,144,192)' ...
    ) ...
  );

data2=data1;
data2.y = dist2;
data2.name = 'Sammon Mapping';
data2.marker.symbol = 'cross';
data2.marker.color = 'rgb(144,192,54)';

data3=data1;
data3.y = dist3;
data3.name = 'Squared Stress';
data3.marker.symbol = 'square';
data3.marker.color = 'rgb(192,54,144)';

% set up axis styles
axesstyle_x = struct( ...
    'zeroline' , false, ...
    'title' , 'Dissimilarities' ...
);
axesstyle_y = struct( ...
    'zeroline' , false, ...
    'title' , 'Distances' ...
);

% set the legend style
legendstyle = struct('x' , 0, 'y' , 1); % Top left

% set up layout
layout = struct( ...
    'title', 'Morse Signal Analysis', ...
    'xaxis' , axesstyle_x, ...
    'yaxis' , axesstyle_y, ...
    'legend' , legendstyle, ...
    'hovermode', 'closest' ...
);
 
% send graph request
response = plotly({data1, data2, data3}, struct('layout', layout, ...
    'filename', 'morse_signal','fileopt', 'overwrite'))


response = 

         url: 'https://plot.ly/~andreyDim/142'
     message: [1x0 char]
     warning: [1x0 char]
    filename: 'morse_signal'
       error: [1x0 char]

The plotly MATLAB command sends data to my plotly account and returns the unique url https://plot.ly/~andreyDim/142 where anyone can view the rendered graph.

Every plotly graph URL can be embedded in HTML as wrapped in an IFrame. Here's a quick 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)

Let's see the the graph:


In [5]:
show_plot('https://plot.ly/~andreyDim/142')


Out[5]:

Sweet! Let's keep going...

EXAMPLE 2: Gain vs Frequency


In [6]:
%%matlab
% Prepare plotly environment
clear all
api_path = 'C:\Users\Andrey\Dropbox\ANDREY\PLOTLY\API_matlab\plotly';
addpath(genpath(api_path))
signin('andreyDim', 'r0x3w3ivg4');

% Create a set of values for the damping factor
zeta = [0.01 .02 0.05 0.1 .2 .5 1 ];

% Create a range of frequency values equally spaced logarithmically
w = logspace(-1, 1, 1000);

% Define a color for each damping factor
colors = {'red' 'green' 'blue' 'lightblue' 'purple' 'lightgreen' 'fuchsia'};

% Create PLOTLY data structs
data = cell(1,7);

% Produce gain vs. frequency for each of the seven damping factors
for i = 1:7
    a = w.^2 - 1;
    b = 2*w*zeta(i);
    gain = sqrt(1./(a.^2 + b.^2));
    
    
    data{i} = struct(...
  'x', w, ...
  'y', gain, ...
  'type', 'scatter', ...
  'name', ['$\\zeta = ' num2str(zeta(i)) '$'], ...
  'mode', 'lines', ...
  'line', struct('color',colors{i},...
        'width',3) ...
  );
    
end

% set axis styles
axesstyle_x = struct( ...
    'type' , 'log', ...
    'range' , [-1, 1], ...
    'linewidth' , 2, ...
    'title' , '$\\text{Frequency } \\omega$' ...
);
axesstyle_y = struct( ...
    'type' , 'log', ...
    'range' , [-2, 2], ...
    'linewidth' , 2, ...
    'title' , '$\\text{Gain}$' ...
);

% set up legend style
legendstyle = struct( ...
  'x' , 0, ...
  'y' , 1, ...
  'bgcolor' , '#E2E2E2', ... 
  'bordercolor' , '#FFFFFF', ...
  'borderwidth' , 2, ...
  'traceorder' , 'normal' ...
  );

% set layout style
layout = struct( ...
    'title', '$\\text{Gain vs Frequency } \\omega$', ...
    'xaxis' , axesstyle_x, ...
    'yaxis' , axesstyle_y, ...
    'legend', legendstyle, ...
    'hovermode', 'closest' ...
);

% send graph request
response = plotly(data, struct('layout', layout, ...
    'filename','gain_frequency', ...
	'fileopt', 'overwrite'))


response = 

         url: 'https://plot.ly/~andreyDim/139'
     message: [1x0 char]
     warning: [1x0 char]
    filename: 'gain_frequency'
       error: [1x0 char]


In [7]:
show_plot('https://plot.ly/~andreyDim/139')


Out[7]:

EXAMPLE 3: Tuberculosis Cases


In [9]:
%%matlab

% Prepare plotly environment
clear all
api_path = 'C:\Users\Andrey\Dropbox\ANDREY\PLOTLY\API_matlab\plotly';
addpath(genpath(api_path))
signin('andreyDim', 'r0x3w3ivg4');

% Create the data for the plots
TBdata = [1990 4889 16.4; 1991 5273 17.4; 1992 5382 17.4; 1993 5173 16.5;
          1994 4860 15.4; 1995 4675 14.7; 1996 4313 13.5; 1997 4059 12.5;
          1998 3855 11.7; 1999 3608 10.8; 2000 3297  9.7; 2001 3332  9.6;
          2002 3169  9.0; 2003 3227  9.0; 2004 2989  8.2; 2005 2903  7.9;
          2006 2779  7.4; 2007 2725  7.2];

years = TBdata(:,1);
cases = TBdata(:,2);
rate  = TBdata(:,3);

% specify the style of each trace
data1 = struct('name', 'Cases', ...
    'opacity', 1.0, ...
  'x', TBdata(:,1), ...
  'y', TBdata(:,2), ...
  'xaxis','x', ...
  'yaxis','y', ...
  'type', 'bar', ...
  'marker', struct(...
    'color', 'white') ...
);

data2 = struct('name', 'Infection rate in cases per thousand', ...
    'opacity', 1.0, ...
  'x', TBdata(:,1), ...
  'y', TBdata(:,3), ...
  'xaxis','x', ...
  'yaxis','y2', ...
  'type', 'scatter', ...
  'mode', 'lines', ...
  'line', struct('color', 'purple', 'size', 2) ...
  );

% set the axis styles
axesstyle_x = struct( ...
    'title' , 'Years' ...
);
axesstyle_y = struct( ...
    'range', [0 6000], ...
    'ticks' , '', ...
    'title' , 'Cases' ...
);
axesstyle_y2 = struct( ...
    'showgrid' , false, ...
    'ticks' , '', ...
    'range', [6 18], ...
    'titlefont',struct( ...
         'color','purple' ...
      ), ...
      'tickfont',struct( ...
         'color','purple' ...
      ), ...
    'overlaying','y', ...
    'side','right', ...
    'title' , 'Infection rate in cases per thousand' ...
);

% set the layout style
layout = struct( ...
    'title', 'Tuberculosis Cases: 1991-2007', ...
    'xaxis' , axesstyle_x, ...
    'yaxis' , axesstyle_y, ...
    'yaxis2', axesstyle_y2, ...
    'plot_bgcolor', '#c7c7c7', ...
    'showlegend', false ...
);
 
% send graph request
response = plotly({data1, data2}, struct('layout', layout, ...
    'filename','Tuberculosis_cases', ...
	'fileopt', 'overwrite'))


response = 

         url: 'https://plot.ly/~andreyDim/143'
     message: [1x0 char]
     warning: [1x0 char]
    filename: 'Tuberculosis_cases'
       error: [1x0 char]


In [10]:
show_plot('https://plot.ly/~andreyDim/143')


Out[10]:

EXAMPLE 4: Curve Fit


In [12]:
%%matlab
%set up plotly environment
clear all
api_path = 'C:\Users\Andrey\Dropbox\ANDREY\PLOTLY\API_matlab\plotly';
addpath(genpath(api_path))
signin('andreyDim', 'r0x3w3ivg4');

% Load the data for x, y, and yfit
load 'C:\Users\Andrey\Dropbox\ANDREY\PLOTLY\Matlab_Examples\Curve_Fit_with_Confidence_Bounds\fitdata'

% set up scatter of samples
data1 = struct('name', 'Samples', ...
    'opacity', 1.0, ...
  'x', x, ...
  'y', y, ...
  'type', 'scatter', ...
  'mode', 'markers', ...
  'marker', struct('color', 'black') ...
  );

% set up curve fit
data2=data1;
data2.y = yfit;
data2.name = 'Localized Regression';
data2.mode = 'lines';
data2.line = struct('color', 'red', 'width', 4);

% set up confidence intervals
data3 = data2;
data3.y = yfit+0.3;
data3.name = 'Confidence Interval';
data3.line = struct('color', 'purple', 'width', 1, 'dash', 'dashdot');

data4 = data3;
data4.fill = 'tonexty';
data4.y = yfit-0.3;

% set the axis style
axesstyle = struct( ...
    'zeroline' , false, ...
    'ticks' , '', ...
    'linecolor' , '#636363', ...
    'linewidth' , 2 ...
);

% set the layout style
layout = struct( ...
    'title', 'Curve Fit Visualization', ...
    'xaxis' , axesstyle, ...
    'yaxis' , axesstyle, ...
    'hovermode', 'closest', ...
    'showlegend', false ...
);

% send graph request
response = plotly({data1, data2, data3, data4}, struct('layout', layout, ...
    'filename','curve_fit_confidence', ...
	'fileopt', 'overwrite'))


response = 

         url: 'https://plot.ly/~andreyDim/138'
     message: [1x0 char]
     warning: [1x0 char]
    filename: 'curve_fit_confidence'
       error: [1x0 char]


In [13]:
show_plot('https://plot.ly/~andreyDim/138')


Out[13]:

EXAMPLE 5: Spline and Convex Hull Property


In [14]:
%%matlab
%set up plotly environment
clear all
api_path = 'C:\Users\Andrey\Dropbox\ANDREY\PLOTLY\API_matlab\plotly';
addpath(genpath(api_path))
signin('andreyDim', 'r0x3w3ivg4');

% Load the points for creating a spline curve
load 'C:\Users\Andrey\Dropbox\ANDREY\PLOTLY\Matlab_Examples\Add_Text_to_Plot_1\splineData'

% set up text
text = cell(1,size(points,1));
for i=1:numel(text)
   text{i} = ['Point ' num2str(i)];     
end

% set up scatter data
data1 = struct( ...
    'name', 'Control Points', ...
    'x', points(:,1), ...
    'y', points(:,2), ...
    'marker', struct( ...
    'color', 'red'), ...
    'mode', 'lines+markers+text',...
    'line', struct('color', 'black', 'width', 1, 'dash', 'dot'), ...
    'text', {text}, ...
    'textposition', 'top'...
    );

% set up spline
data2 = struct( ...
    'name', 'Spline', ...
    'x', x, ...
    'y', y, ...
    'mode', 'lines',...
    'line', struct('color', 'red', 'width', 3) ...
    );


% set the axis style
axesstyle = struct( ...
    'showgrid' , false, ...
    'zeroline' , false, ...
    'showticklabels' , false, ...
    'ticks' , '', ...
    'linecolor' , '#636363', ...
    'linewidth' , 3 ...
);

% set the layout style
layout = struct( ...
    'title', 'The Convex-Hull Property', ...
    'xaxis' , axesstyle, ...
    'yaxis' , axesstyle, ...
    'hovermode', 'closest', ...
    'showlegend', false ...
);
 
% send graph request
response = plotly({data1, data2}, struct('layout', layout, ...
    'filename', 'convex_hull', 'fileopt','overwrite'))


response = 

         url: 'https://plot.ly/~andreyDim/141'
     message: [1x0 char]
     warning: [1x0 char]
    filename: 'convex_hull'
       error: [1x0 char]


In [15]:
show_plot('https://plot.ly/~andreyDim/141')


Out[15]:

EXAMPLE 6: Undersea Elevation


In [16]:
%%matlab
% set up plotly environment
clear all

api_path = 'C:\Users\Andrey\Dropbox\ANDREY\PLOTLY\API_matlab\plotly';
addpath(genpath(api_path))
signin('andreyDim', 'r0x3w3ivg4');

% Load undersea elevation data
load seamount x y z;

% set up color map for z values
step_size = (max(z)-min(z))/99;
map_idx = ceil((z - min(z))/step_size)+1;
color_map = jet(100);

colors = cell(1,numel(x));
for i=1:numel(x)
colors{i} = ['rgb(' num2str(floor(255*color_map(map_idx(i),1))) ',' ...
    num2str(floor(255*color_map(map_idx(i),2))) ',' ...
    num2str(floor(255*color_map(map_idx(i),3))) ')'];
end

% set up scatter data
data = struct( ...
    'x', x, ...
    'y', y, ...
    'marker', struct( ...
    'color', {colors}), ...
    'mode', 'markers' ...
    );



% set the axis styles
axesstyle_x = struct( ...
    'title' , 'Longitude' ...
);
axesstyle_y = struct( ...
    'title' , 'Latitude' ...
);


% set the layout style
layout = struct( ...
    'title', 'Undersea Elevation', ...
    'xaxis' , axesstyle_x, ...
    'yaxis' , axesstyle_y, ...
    'hovermode', 'closest', ...
    'showlegend', false ...
);
 
% send graph request
response = plotly(data, struct('layout', layout, ...
    'filename', 'undersea_elevation','fileopt', 'overwrite'))


response = 

         url: 'https://plot.ly/~andreyDim/140'
     message: [1x0 char]
     warning: [1x0 char]
    filename: 'undersea_elevation'
       error: [1x0 char]


In [17]:
show_plot('https://plot.ly/~andreyDim/140')


Out[17]:

In [ ]: