5.18.2012

Plotting a two-dimensional line using color to depict a third dimension (in Matlab)

I had seen other people do this in publications, but was annoyed that I couldn't find a quick function to do it in a general case. So I'm sharing my function to do this.

If you have three vectors describing data, eg. lat, lon and windspeed of Hurricane Ivan (yes, this data is from my env. sci. labs), you could plot it in 3 dimensions, which is awkward for readers:


or using my nifty script, you can plot wind speed as a color in two dimensions:


Not earth-shattering, but useful. Next week, I will post an earth-shattering application.

[BTW, if someone sends me code to do the same thing in Stata, I will be very grateful.]

Also, you can make art:


Help file below the fold.

% -----------------------
%
% S. HSIANG 
% 5.11.2012
% SHSIANG@PRINCETON.EDU
%
% -----------------------
%
% PLOT_COLORED_LINE(X,Y,C) plots the line X vs. Y where the color of the
% segments are determed by values in C.  If no color is specified, then the
% line is plotted greyscale, with the lowest values set to [almost] white 
% and the highest values set to [almost] black.
%
% PLOT_COLORED_LINE(X,Y,C,V1) plots values scaled between almost white (low
% values) and the color specified by the three element vector V1 for high
% values.
%
% PLOT_COLORED_LINE(X,Y,C,V1,V0) plots values scaled between V0 (low
% values) and V1 (high values). Both V1 and V0 are three element vectors
% specifying a color (with entries between zero and one).  They can be 
% interchanged and the function will still plot, but the color scale will
% be reversed.
%
% PLOT_COLORED_LINE(X,Y,C,V1,V0,WIDTH) sets the line width to WIDTH
%
% Example: 
%
%       x = [1:.1:100]
%       y = sin(x)
%       c = cos(x)
%       plot_colored_line(x,y,y)
%       plot_colored_line(x,y,c,[0 0 1], [1 0 0], 3)
%

1 comment:

  1. Thanks! It's very helpful! I have one question. How can I create a color bar for the 3rd dimension if using your function?

    Thanks!

    ReplyDelete