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 original example can be found at the Matlab Plot Gallery
First, start a MATLAB server:
import pymatbridge as pymat
ip = get_ipython()
pymat.load_ipython_extension(ip,
matlab='C:\Users\Andrey\matlab_shortcut.lnk')
Starting MATLAB on http://localhost:60577 visit http://localhost:60577/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 connects to Plot.ly, generates the necessary data structures, and sends the graph request. The response is the url where the plot is located.
%%matlab
clear all
% Prepare PLOTLY environment
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', ['damping: ' num2str(zeta(i))], ...
'mode', 'lines', ...
'line', struct('color',colors{i},...
'width',3) ...
);
end
% set axis styles
axesstyle_x = struct( ...
'type' , 'log', ...
'range' , [-1, 1], ...
'title' , 'Frequency' ...
);
axesstyle_y = struct( ...
'type' , 'log', ...
'range' , [-2, 2], ...
'title' , 'Gain' ...
);
% set layout style
layout = struct( ...
'title', 'Gain VS Frequency', ...
'xaxis' , axesstyle_x, ...
'yaxis' , axesstyle_y, ...
'hovermode', 'closest' ...
);
response = plotly(data, struct('layout', layout));
url = response.url
filename = response.filename
url = https://plot.ly/~andreyDim/110 filename = plot from API (62)
The plotly
MATLAB command sends data to my plotly account and returns the unique url https://plot.ly/~andreyDim/110 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.
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:
show_plot('https://plot.ly/~andreyDim/110')