*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')

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

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

*command at the end of the code will convert the current figure into a format that Plotly understands and publish it.*

**fig2plotly**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'.

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>

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)

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

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();

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]:

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

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

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.