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

December 4, 2013 4 Comments

I would like to welcome Chris Parmer of plot.ly, who will describe the integration of Plotly graphs and charts in Matlab. Unlike the open-source JFreeChart and Waterloo plotting libraries that were described here in the past, Plotly is a commercial (not open-source) service. Contact Plotly for the exact license terms and costs. However, as you can see below, there’s a demo account that you can freely use. While I do not directly endorse Plotly as a commercial operation, I love its beautiful visualizations and interactivity. I think MathWorks would be wise to copy ideas from Plotly to Matlab’s graphics library, esp. new chart types and the interactivity features. In the future I hope that either Plotly concepts get included in Matlab’s HG, or that Plotly plots become embeddable in Matlab GUI (or both).
Plotly is a new web-based graphing application. You can interactively make, style, analyze and share beautiful graphs. Here is an example (move your mouse over the graph to see the interactive effects): 


Full size: https://plot.ly/~chris/1638/


Additional examples: https://plot.ly/~bchartoff/603/, https://plot.ly/~jackp/1000/ and Washington Post.

Creating Plotly graphs in Matlab

Plotly has a Matlab interface. From Matlab, you send data to plotly where it will be stored and made into a graph that you view in your browser. Let’s get started.

  1. download the Plotly-Matlab API package.
     
  2. Add folder and subfolders to your Matlab path:
    path_to_downloaded_folder = '/User/chris/Downloads/plotly'; % fill in with your path
    addpath(genpath(path_to_downloaded_folder))

    path_to_downloaded_folder = '/User/chris/Downloads/plotly'; % fill in with your path addpath(genpath(path_to_downloaded_folder))

  3. Sign up through the API, or sign-in with a demo account:
    % To sign up, run:
    r = signup('my_desired_plotly_username', 'my_desired_plotly_username@my_email.com') % plotly generates a temp password and api_key for you
    signin(r.un, r.api_key); % then, sign in with your newly created account
    % OR to use the demo account, do:
    plotly_username = 'MATLAB_example' % a demo username you can use
    plotly_key = 'h5n38rzyjo' % a demo api key you can use
    signin(plotly_username, plotly_key)  % sign in to plotly

    % To sign up, run: r = signup('my_desired_plotly_username', 'my_desired_plotly_username@my_email.com') % plotly generates a temp password and api_key for you signin(r.un, r.api_key); % then, sign in with your newly created account % OR to use the demo account, do: plotly_username = 'MATLAB_example' % a demo username you can use plotly_key = 'h5n38rzyjo' % a demo api key you can use signin(plotly_username, plotly_key)  % sign in to plotly

  4. Create a new chart using the API’s plotly function:
    % Here's a simple line chart example:
    >> x = linspace(0, 6*pi, 100);
    >> y1 = exp(-0.2*x).*sin(x);
    >> y2 = exp(-0.3*x).*sin(x);
    >> r = plotly(x,y1,x,y2) % call plotly instead of plot
    High five! You successfully sent some data to your account on plotly.
    View your plot in your browser at https://plot.ly/~MATLAB_example/3 or inside your plot.ly account where it is named 'plot from API (3)'
    ans =
       url: 'https://plot.ly/~MATLAB_example/3'
       message: [1x205 char]
       warning: [1x0 char]
       filename: 'plot from API (3)'
       error: [1x0 char]

    % Here's a simple line chart example: >> x = linspace(0, 6*pi, 100); >> y1 = exp(-0.2*x).*sin(x); >> y2 = exp(-0.3*x).*sin(x); >> r = plotly(x,y1,x,y2) % call plotly instead of plot High five! You successfully sent some data to your account on plotly. View your plot in your browser at https://plot.ly/~MATLAB_example/3 or inside your plot.ly account where it is named 'plot from API (3)' ans = url: 'https://plot.ly/~MATLAB_example/3' message: [1x205 char] warning: [1x0 char] filename: 'plot from API (3)' error: [1x0 char]

And here’s the graph that you just generated: https://plot.ly/~MATLAB_example/3
Note that the graph won’t actually appear in a Matlab figure, nor can it be viewed in Matlab’s limited built-in browser (web). Instead, you view all of your plots in your “real” web browser, at the URL that plotly has returned. You can also have Matlab automatically open up the browser by running dos(['open ' r.url]) on a Mac, or dos(['start ' r.url]) on Windows. Within a webpage, you can embed it using an iframe tag (as I have done in this article), as follows:

<iframe width="800" height="400" seamless="seamless" scrolling="no" src="https://plot.ly/~MATLAB_example/3"></iframe>

<iframe width="800" height="400" seamless="seamless" scrolling="no" src="https://plot.ly/~MATLAB_example/3"></iframe>

Here is a side-by-side comparison with the corresponding Matlab plot:

Corresponding Matlab and Plotly plots (click for details)
Corresponding Matlab and Plotly plots (click for details)

Customizing Plotly graphs

Every aspect of the plotly graph can be customized online. This means no more 500-line styling scripts! To open up the plot into the GUI, click the “Save a copy” button. You can also download the graphs to EPS, SVG, PNG, and PDF:

Web-based Plotly chart customization (click for details)
Web-based Plotly chart customization (click for details)

Plotly can make line charts, scatter plots, histograms, 2D histograms, box plots, heatmaps, and error bars. They also support log axes, date axes, multiple axes and subplots.
Plotly’s graphing syntax is a little unconventional. Plots are described with cell arrays of structs. Each struct describes a single “trace” of the plot with data, chart-type, and optional styling information. There are no setters or getters (Why? Well, because behind the scenes, the data gets converted to a JSON object and the closest analogue of a JSON array of key-value pair objects in Matlab is a cell array of structs). For example:

samples = randn(500,1); % 500 normally distributed samples
trace1 = struct('y', samples, ...
                'type', 'histogramy', ... % make a histogram type plot
                'histnorm', 'probability density'); % normalized by probability density distribution
trace2 = struct('x', linspace(-3,3,100), ...
                'y', 1./sqrt(2*pi)*exp(-linspace(-3,3,100).^2/2.), ...
                'fill', 'tozeroy') % "fill" the curve to the "zero-y" line i.e. make an area plot
response = plotly({trace1, trace2});  % => https://plot.ly/~MATLAB_example/5

samples = randn(500,1); % 500 normally distributed samples trace1 = struct('y', samples, ... 'type', 'histogramy', ... % make a histogram type plot 'histnorm', 'probability density'); % normalized by probability density distribution trace2 = struct('x', linspace(-3,3,100), ... 'y', 1./sqrt(2*pi)*exp(-linspace(-3,3,100).^2/2.), ... 'fill', 'tozeroy') % "fill" the curve to the "zero-y" line i.e. make an area plot response = plotly({trace1, trace2}); % => https://plot.ly/~MATLAB_example/5


Now let’s make some graphs not generally seen in Matlab 🙂
First, triple y-axis:

x = linspace(0,6*pi,100);
trace1 = struct('x',x, 'y',sin(x).*exp(-0.3*x));
trace2 = struct('x',x, 'y',10*sin(x-2*pi/3).*exp(-0.3*x), 'yaxis','y2'); % this trace will correspond to 2nd y-axis, 'y2'
trace3 = struct('x',x, 'y',100*sin(x-4*pi/3).*exp(-0.3*x), 'yaxis','y3'); % this trace will correspond to 3rd y-axis, 'y3'
layout = struct('xaxis', struct('domain',[0,0.9]), ... % set x-axis to span 90% of plot width, like Matlab's 'Position' property
                'yaxis2', struct('anchor','x', 'side','right', 'overlaying','y'), ... % places another y-axis on the right side of the plot
                'yaxis3', struct('anchor','side', 'right','free', 'position',1.0, 'overlaying','y')) % places 3rd y-axis at 100% plot width
r = plotly({trace1, trace2, trace3}, struct('layout', layout));  % => https://plot.ly/~MATLAB_example/13
dos(['open ', r.url])

x = linspace(0,6*pi,100); trace1 = struct('x',x, 'y',sin(x).*exp(-0.3*x)); trace2 = struct('x',x, 'y',10*sin(x-2*pi/3).*exp(-0.3*x), 'yaxis','y2'); % this trace will correspond to 2nd y-axis, 'y2' trace3 = struct('x',x, 'y',100*sin(x-4*pi/3).*exp(-0.3*x), 'yaxis','y3'); % this trace will correspond to 3rd y-axis, 'y3' layout = struct('xaxis', struct('domain',[0,0.9]), ... % set x-axis to span 90% of plot width, like Matlab's 'Position' property 'yaxis2', struct('anchor','x', 'side','right', 'overlaying','y'), ... % places another y-axis on the right side of the plot 'yaxis3', struct('anchor','side', 'right','free', 'position',1.0, 'overlaying','y')) % places 3rd y-axis at 100% plot width r = plotly({trace1, trace2, trace3}, struct('layout', layout)); % => https://plot.ly/~MATLAB_example/13 dos(['open ', r.url])


Try clicking and dragging on the y-axis (along the number lines). Notice how each axes is totally independent of the other trace. Panning is done by dragging the x-axis. Also, try zooming (click-and-drag).
Here’s another neat example of how subplots’ axes can be linked to each other or can be independent:

x1 = [1, 2, 3];  y1 = [2,3,4];
x2 = [20,30,40]; y2 = [3,4,5];
x3 = [2, 3, 4];  y3 = [600,700,800];
x4 = [4000,5000,6000]; y4 = [7000,8000,9000];
% build structs describing the plot traces and assigning data to axes
trace1 = struct('x',x1, 'y',y1);
trace2 = struct('x',x2, 'y',y2, 'xaxis','x2', 'yaxis','y');  % new x-axis but same y-axis as trace1; 'x2' is shorthand for 'xaxis2' below
trace3 = struct('x',x3, 'y',y3, 'xaxis','x',  'yaxis','y3'); % same x-axis as trace 1 but a new y-axis
trace4 = struct('x',x4, 'y',y4, 'xaxis','x4', 'yaxis','y4'); % new x-axis and new y-axis
% build a layout struct describing the layout of the different axes
xaxis =  struct('domain', [0, 0.45]); % let the first x-axis span the first 45% of the plot width
yaxis =  struct('domain', [0, 0.45]); % and let the first y-axis span the first 45% of the plot height
xaxis2 = struct('domain', [0.55, 1]); % and let the second axis span the latter 45% of the plot width
yaxis3 = struct('domain', [0.55,1]);
xaxis4 = struct('domain', [0.55, 1], 'anchor','y4'); % anchor axis vertical position to start of yaxis4
yaxis4 = struct('domain', [0.55, 1], 'anchor','x4'); % anchor axis horizontal position to start of xaxis4
layout = struct('xaxis',xaxis, 'yaxis',yaxis, 'xaxis2',xaxis2, 'yaxis3',yaxis3, 'xaxis4',xaxis4, 'yaxis4',yaxis4);
r = plotly({trace1,trace2,trace3,trace4}, struct('=> layout', layout))  % => https://plot.ly/~MATLAB_example/15
dos(['open ', r.url])

x1 = [1, 2, 3]; y1 = [2,3,4]; x2 = [20,30,40]; y2 = [3,4,5]; x3 = [2, 3, 4]; y3 = [600,700,800]; x4 = [4000,5000,6000]; y4 = [7000,8000,9000]; % build structs describing the plot traces and assigning data to axes trace1 = struct('x',x1, 'y',y1); trace2 = struct('x',x2, 'y',y2, 'xaxis','x2', 'yaxis','y'); % new x-axis but same y-axis as trace1; 'x2' is shorthand for 'xaxis2' below trace3 = struct('x',x3, 'y',y3, 'xaxis','x', 'yaxis','y3'); % same x-axis as trace 1 but a new y-axis trace4 = struct('x',x4, 'y',y4, 'xaxis','x4', 'yaxis','y4'); % new x-axis and new y-axis % build a layout struct describing the layout of the different axes xaxis = struct('domain', [0, 0.45]); % let the first x-axis span the first 45% of the plot width yaxis = struct('domain', [0, 0.45]); % and let the first y-axis span the first 45% of the plot height xaxis2 = struct('domain', [0.55, 1]); % and let the second axis span the latter 45% of the plot width yaxis3 = struct('domain', [0.55,1]); xaxis4 = struct('domain', [0.55, 1], 'anchor','y4'); % anchor axis vertical position to start of yaxis4 yaxis4 = struct('domain', [0.55, 1], 'anchor','x4'); % anchor axis horizontal position to start of xaxis4 layout = struct('xaxis',xaxis, 'yaxis',yaxis, 'xaxis2',xaxis2, 'yaxis3',yaxis3, 'xaxis4',xaxis4, 'yaxis4',yaxis4); r = plotly({trace1,trace2,trace3,trace4}, struct('=> layout', layout)) % => https://plot.ly/~MATLAB_example/15 dos(['open ', r.url])


The bottom two plots share the same y-axis, the two stacked plots on the left share the same y-axis, the two stacked plots on the left share the same x-axis and the plot in the top right has its own x and y axes. Try zooming (click-and-drag), auto-scaling (double-click), or axis panning (click-and-drag on the axes number lines) around in the different plots and see how the axes respond.
In case you don’t have the Matlab Stats toolbox, you can use plotly to make your box plots:

y1 = randn(50,1); y2 = rand(50,1);
r = plotly({struct('y',y1, 'type','box'), struct('y',y2, 'type','box')}) % => https://plot.ly/~MATLAB_example/17
dos(['open ', r.url])

y1 = randn(50,1); y2 = rand(50,1); r = plotly({struct('y',y1, 'type','box'), struct('y',y2, 'type','box')}) % => https://plot.ly/~MATLAB_example/17 dos(['open ', r.url])


In case you don’t have the Matlab Bioinformatics toolbox or Yair’s DataMatrix utility, you can use plotly to make your heatmaps:

r = plotly({struct('z',randn(50,50), 'type','heatmap')}) % => https://plot.ly/~matlab_example/18
dos(['open ', r.url])

r = plotly({struct('z',randn(50,50), 'type','heatmap')}) % => https://plot.ly/~matlab_example/18 dos(['open ', r.url])


Or, a different type of heat-map (click here for details):

This was an introduction to the plotly-Matlab interface. Plotly is bridging desktop-based technical computing with the modern web. Inside the tool itself, you can share graphs and data with others (similarly to Google Docs), view revisions of your graph and data (similarly to GitHub), and even make graphs without coding by uploading a CSV, Excel, or even a .mat file. Since it’s entirely web-based, you can share your graphs and data with a link to anyone, even if they don’t have Matlab. There are also similar interfaces in Python, R, Perl, Julia, and Arduino, so if you or if you and your colleagues like to work in different languages, you can keep all of your data and graphs in the same place, online.
Last but not least, it’s much easier to make beautiful, publication-quality graphs. Here are some of our favorite examples:
Graphs: plot.ly/~carmeloosh/66/, plot.ly/~flann321/9/, plot.ly/~carmeloosh/81/, plot.ly/~carmeloosh/83/, plot.ly/~demos/444, plot.ly/~demos/390
Scripts: plot.ly/MATLAB/script-demos/fractal-barnsley-fern-graph-example/, plot.ly/MATLAB/script-demos/math-scores-boxplot-line-chart-example/

Additional resources

  • Online-documentation: https://plot.ly/api/MATLAB/
  • An online gallery: https://plot.ly/api/MATLAB/gallery/
  • Plotly File Exchange utility: http://www.mathworks.com/matlabcentral/fileexchange/42202-plotly-api
  • The Matlab interface is open source on GitHub: https://github.com/plotly/MATLAB-api (note that the plotly engine is not open-source, only the API)
  • Plotly’s homepage: https://plot.ly/
  • Email: chris [at] plot [dot] ly

Related posts:

  1. Plotly graphs in IPython Notebook – Plotly graphs can be embedded in an IPython Notebook directly from 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 histogram plots – Basic bar charts and histogram plots can be customized in important aspects. ...
  5. 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. ...
  6. Specialized Matlab plots – The new MathWorks Plot Gallery provides access to some plotting examples on the File Exchange. Numerous others are available, extending the customizability of Matlab graphics. ...
Commercial Plotly
Print Print
« Previous
Next »
4 Responses
  1. Jveer December 6, 2013 at 10:30 Reply

    Great job guys!

    Any chance of seeing 3D plots any time soon? To the very least 3D scatter plots?

  2. Emad (Matlab junkie) January 9, 2014 at 22:32 Reply

    This is awesome. Definitely going to use this!

  3. varun chopra February 28, 2014 at 11:35 Reply

    amazing!!!

  4. What are some cool MATLAB tricks? | TechNote August 5, 2015 at 07:28 Reply

    […] Plug in with the Plotly MATLAB Graphing Library to make interactive web based graphs. See demo for code and interactive graphs: Plotly graphs | Undocumented Matlab. […]

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
ActiveX (6) 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) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
  • Nicholas (3 days 20 hours ago): Hi Yair, Thanks for the reply. I am on Windows 10. I also forgot to mention that this all works wonderfully out of the editor. It only fails once compiled. So, yes, I have tried a...
  • Nicholas (3 days 20 hours ago): Hi Yair, Thanks for the reply. I am on Windows 10. I also forgot to mention that this all works wonderfully out of the editor. It only fails once compiled. So, yes, I have tried a...
  • Yair Altman (4 days 3 hours ago): Nicholas – yes, I used it in a compiled Windows app using R2022b (no update). You didn’t specify the Matlab code location that threw the error so I can’t help...
  • Nicholas (4 days 23 hours ago): Hi Yair, Have you attempted your displayWebPage utility (or the LightweightHelpPanel in general) within a compiled application? It appears to fail in apps derived from both R2022b...
  • João Neves (8 days 4 hours ago): I am on matlab 2021a, this still works: url = struct(struct(struct(struct(hF ig).Controller).PlatformHost). CEF).URL; but the html document is empty. Is there still a way to do...
  • Yair Altman (11 days 2 hours ago): Perhaps the class() function could assist you. Or maybe just wrap different access methods in a try-catch so that if one method fails you could access the data using another...
  • Jeroen Boschma (11 days 5 hours ago): Never mind, the new UI components have an HTML panel available. Works for me…
  • Alexandre (11 days 6 hours ago): Hi, Is there a way to test if data dictionnatry entry are signal, simulink parameters, variables … I need to access their value, but the access method depends on the data...
  • Nicholas (11 days 20 hours ago): In case anyone is looking for more info on the toolbar: I ran into some problems creating a toolbar with the lightweight panel. Previously, the Browser Panel had an addToolbar...
  • Jeroen Boschma (15 days 3 hours ago): I do not seem to get the scrollbars (horizontal…) working in Matlab 2020b. Snippets of init-code (all based on Yair’s snippets on this site) handles.text_explorer...
  • Yair Altman (43 days 5 hours ago): m_map is a mapping tool, not even created by MathWorks and not part of the basic Matlab system. I have no idea why you think that the customizations to the builtin bar function...
  • chengji chen (43 days 12 hours ago): Hi, I have tried the method, but it didn’t work. I plot figure by m_map toolbox, the xticklabel will add to the yticklabel at the left-down corner, so I want to move down...
  • Yair Altman (51 days 5 hours ago): @Alexander – this is correct. Matlab stopped including sqlite4java in R2021b (it was still included in 21a). You can download the open-source sqlite4java project from...
  • Alexander Eder (57 days 0 hours ago): Unfortunately Matlab stopped shipping sqlite4java starting with R2021(b?)
  • K (63 days 11 hours ago): Is there a way to programmatically manage which figure gets placed where? Let’s say I have 5 figures docked, and I split it into 2 x 1, I want to place 3 specific figures on the...
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