® library in MATLAB /> ® library in MATLAB />

User Guide for Plotlys MATLAB® Library in MATLAB®

How to use the core functions of Plotlys Matlab Open Source Graphing Library

Plotly is a browser-based data analysis and visualization tool that lets you and your team make and share beautiful, interactive graphs, 3D graphs, and streaming graphs via the open source JavaScript graphing library plotly.js.
This API allows MATLAB® users to generate Plotly graphs from the desktop MATLAB® environment: turning MATLAB® figures into interactive, shareable, collaborative projects.
For more information on how to create specific chart types see our documentation examples.

Initial Setup¶

The Plotly Graphing Library for MATLAB® has been embedded into our MATLAB® toolboxes and our Plotly credentials have been saved using plotlysetup.m. In order to start using the Plotly Graphing Library for MATLAB® API all we have to do now is start MATLAB! More information regarding installation / setting up the Plotly Graphing Library for MATLAB® API can be found on the online documentation.

How It Works¶

Plotly charts are described declaratively with struct and cell array objects. For an extensive list of the keys used to describe plotly graphs see our reference page. To get an idea of how the MATLAB® API works, check out this simple example of how to translate a MATLAB® figure, modify some attributes, and then send it to Plotly.

In [ ]:
>> x = linspace(-2*pi, 2*pi);
>> y1 = sin(x);
>> y2 = cos(x);
>> plot(x, y1, x, y2);

%% Translate the figure from MATLAB to Plotly
>> fig = plotlyfig(gcf);

>> fig.PlotOptions.Strip = 0; % If 0, don't strip MATLAB's styling in translation. If 1, strip MATLAB's styling.

>> fig.data
ans =

   [1x1 struct]    [1x1 struct]

>> fig.data{1}    % The 'type' of this trace is 'scatter'. scatter's reference: #scatter
ans =

        xaxis: 'x1'             % more about scatter's 'xaxis': #scatter-xaxis
        yaxis: 'y1'             % scatter's 'yaxis' property:   #scatter-yaxis
         type: 'scatter'
      visible: 1                % scatter's 'visible' property: #scatter-visible
            x: [1x100 double]   % scatter's 'x' property:       #scatter-x
            y: [1x100 double]   % scatter's 'y' property:       #scatter-y
         name: ''               % scatter's 'name' property:    #scatter-name
         mode: 'lines'          % scatter's 'mode' property:    #scatter-mode
         line: [1x1 struct]     % scatter's 'line' property:    #scatter-line
       marker: [1x1 struct]     % scatter's 'marker' property:  #scatter-marker
   showlegend: 1                % scatter's 'showlegend':       #scatter-marker

%% Modify or add new properties to this trace
>> fig.data{1}.name = 'Current'; % Update the legend name to 'Current'

>> fig.layout     % layout reference: #layout
ans =

        autosize: 0                     % layout's 'autosize':      #layout-autosize
          margin: [1x1 struct]          % layout's 'margin':        #layout-margin
      showlegend: 0                     % layout's 'showlegend':    #layout-showlegend
           width: 840                   % layout's 'width':         #layout-width
          height: 630                   % layout's 'height':        #layout-height
   paper_bgcolor: 'rgb(255,255,255)'    % layout's 'paper_bgcolor': #layout-paper_bgcolor
       hovermode: 'closest'             % layout's 'hovermode':     #layout-hovermode
    plot_bgcolor: 'rgba(0,0,0,0)'       % layout's 'plot_bgcolor':  #layout-plot_bgcolor
          xaxis1: [1x1 struct]          % layout's 'xaxis':         #layout-xaxis
          yaxis1: [1x1 struct]          % layout's 'yaxis':         #layout-yaxis
     annotations: {[1x1 struct]}        % layout's 'annotations':   #layout-annotations

>> fig.layout.showlegend = true;  % layout's 'showlegend':    #layout-showlegend
>> fig.layout.legend = struct('x', 1, 'y', 1); % Update the legend: #layout-legend
>> fig.layout.title = 'Modified plot';

%% Set the filename, and overwrite the plot if it already exists
>> fig.PlotOptions.FileName = 'Customized plot';
>> fig.PlotOptions.FileOpt = 'overwrite';
%% Use offline
%% Download the offline bundle
>> getplotlyoffline('https://cdn.plot.ly/plotly-latest.min.js')
>> fig.PlotOptions.Offline = true;

%% Send to plotly
>> fig.plotly

Core Functions¶

fig2plotly.m: Plot a MATLAB® figure object with Plotly fig2plotly.m converts MATLAB® figures to online Plotly graphs. MATLAB® describes figures differently than Plotly. Plotly's MATLAB® library crawls the MATLAB® figure objects and translates the MATLAB® attributes into the structure that Plotly uses to describe and draw data visualizations.

In [ ]:
resp = fig2plotly()
resp = fig2plotly(f)
resp = fig2plotly(gcf)
resp = fig2plotly(f,'property',value, ... )
resp = fig2plotly(gcf,'property',value, ... )

gcf - root figure object handle [double].
f - root figure object [struct] >> f = get(gcf)

'name' - name of the plot [string]['untitled']
'strip' - use plotly default styling [boolean][0]
'open' - opens a browser with plot result [boolean][1]

resp - results info of the plot [struct]
In [ ]:
api_path = ('/Users/chuckbronson/Documents/PLOTLY/MATLAB_API_DEV/DEV/TEST_PLOTS');

load fitdata x y yfit;
fig = figure;
scatter(x, y, 'k');
line(x, yfit, 'color', 'k', 'linestyle', '-', 'linewidth', 2);
line(x, yfit + 0.3, 'color', 'r', 'linestyle', '--', 'linewidth', 2);
line(x, yfit - 0.3, 'color', 'r', 'linestyle', '--', 'linewidth', 2);
legend('Data', 'Localized Regression', 'Confidence Intervals', 2);

%%Just ONE line of Plotly Code!%%
resp = fig2plotly(fig,'filename','matlab_overview_1','strip',false);

ans = https://plotly.com/~matlab_user_guide/661/noisy-vs-x/

The above plot is the ouptut from calling the scatter.m and line.m functions inherent in MATLAB®. Using the fig2plotly.m function, we are able to extract the relevant data from the MATLAB® figure object and throw the output over to our Plotly account! The returned response variable, resp, is a structure array which contains a url field with the address of our plot.

Offline Usage¶

We can make a Plotly graph in Matlab offline which will be saved as an html file to your current working directory using Plotly Offline. These html files will contain all of the necessary dependencies to render the plot within a browser.

In [ ]:
X = linspace(0,2*pi,50)';
Y = [cos(X), 0.5*sin(X)];


self-hosted matlab online

Retrieve a Figure¶

getplotlyfig.m: Get data, style, and layout from the plots stored online One of Plotly's secret powers is the ability to translate between MATLAB's structure/cell array syntax and JSON. This allows a smooth transition between your figures in MATLAB® and those stored in your Plotly account. getplotlyfig.m allows you to grab the data, style, and layout information from your plots saved online. In fact, getploylyfig.m lets you grab the data, Style and layout of anyone's Plotly plots (as long as they are made public) - not just your own! See a graph you like online? Grab the style, layout, and data and make one for yourself.

In [ ]:
plotlyfigure = getplotlyfig('file_owner',file_id)

file_owner - user name associated with the plot [string].
file_id - number identifier associated with the plot [string]

plotlyfigure - results info of the plot [struct] plotlyfigure.[data,layout]

Here we can use getplotlyfig.m and have a go at changing the bar and line colours on a different graph: https://plotly.com/~matlab_user_guide/664/ !

In [ ]:
%       GET PLOTLY FIG!       %

plotlyfigure = getplotlyfig('matlab_user_guide','664');

%         DATA/STYLE          %

col1 = '#3C8A22';
col2 = '#097054';
col3 = 'black';

plotlyfigure.data{1}.line.width = 10;
plotlyfigure.data{1}.line.color = col2;
plotlyfigure.data{1}.opacity = 0.7;
plotlyfigure.data{1}.name = 'Infection Rate';

plotlyfigure.data{2}.marker.color = col1;
plotlyfigure.data{2}.marker.line.width = 2;
plotlyfigure.data{2}.marker.line.color = col3;
plotlyfigure.data{2}.opacity = 0.7;
plotlyfigure.data{2}.name = 'Cases';

%           LAYOUT            %

plotlyfigure.layout.yaxis2.titlefont.color = col3;
plotlyfigure.layout.yaxis2.tickfont.color = col2;
plotlyfigure.layout.yaxis2.tickcolor = col2;
plotlyfigure.layout.yaxis2.linecolor = col2;
plotlyfigure.layout.yaxis2.linewidth = 2;

plotlyfigure.layout.xaxis.mirror = 0;
plotlyfigure.layout.xaxis.showline = 0;

plotlyfigure.layout.bargap = 0.2;

%             ARGS            %

args.layout = plotlyfigure.layout;
args.filename = 'matlab_overview_5';
args.fileopt = 'overwrite';

%           PLOTLY            %

resp = plotly(plotlyfigure.data,args);

Export Static Image¶

saveplotlyfig.m: save your MATLAB® figure as an image using Plotly. saveplotlyfig.m allows you to convert your MATLAB® figures into static images (.png, .svg, .pdf, .jpeg) using Plotly.

In [ ]:
saveplotlyfig(data, filename, format {otional})
saveplotlyfig(plotlyfigure, filename, format {optional})
NOTE: if format is unspecified, saveplotlyfig will use the image format given by the extension of filename. If filename does not have an explicit extension (ex: filename.pdf), the default format of PNG will be used for the conversion.

data - data/style of plot [cell array]
plotlyfigure.data - data/style of plot [cell array]
plotlyfigure.layout - layout of plot [struct]
filename - name of image to be saved [string]

Image 'filename' of the specified format (PNG, PDF, JPEG, or SVG) saved to your working directory.

Let's have a look at saveplotlyfig.m to see how it works. Check out this next plot that was featured on the MATLAB® plot gallery.

In [ ]:
%            FROM MATLAB® PLOT GALLERY              %
%  http://www.mathworks.com/discovery/gallery.html %

% Load Morse data
load MDdata dissimilarities dist1 dist2 dist3

% Plot the first set of data in blue
fig = figure;
plot(dissimilarities, dist1, 'bo');
hold on;

% Plot the second set of data in red
plot(dissimilarities, dist2, 'r+');

% Plot the third set of data in green
plot(dissimilarities, dist3, 'g^');

% Add title and axis labels
title('Morse Signal Analysis');

%            PLOTLY           %

filename = 'matlab_overview_8';
resp = fig2plotly(fig,'filename',filename,'strip',false);
In [ ]:
plotlyfigure = getplotlyfig('matlab_user_guide','670');
filename = 'morse.png';


Boom! morse.png has been automatically saved to our working directory. Let's have a look.