Monday, April 4, 2011

2D Matlab Plot With A Triangular Domain

I needed to generate a plot in Matlab for data over a triangular domain.  It took quite a lot of googling to find the answer, which ended up being relatively simple, so I thought I'd post the solution here.

The main trick was to use the fill command to draw a triangle over the unwanted parts of the plot.  Note that I also make the background color of the plot white, which I ALWAYS do because the default gray is hideous.  Here's some example code:

clear all;  close all;

x = linspace(-10, 10);
y = linspace(0, 20);
M = randn(length(y), length(x));

figure(1)
set(gcf, 'Color', 'w')
imagesc(x, y, M)
axis image
axis xy
set(gca, 'XAxisLocation', 'Top')
ylabel('X [units]', 'FontName', 'Times', 'FontSize', 14)
xlabel('Y [units]', 'FontName', 'Times', 'FontSize', 14)

hold on
xmin = min(xlim);
xmax = max(xlim);
ymin = min(ylim);
ymax = max(ylim);
h = fill([xmin xmax xmax xmin], [ymin ymin ymax ymin], 'w');
set(gca, 'Box', 'off')
set(h, 'EdgeColor', 'w')
plot([xmin xmax], [ymin ymax], 'k-')

This isn't a perfect solution. Changing the color of the background, plot box, etc, will mess it up.  It worked nicely for my application, though.  Here's what the output of the above looks like.

Your mileage will vary depending upon the renderer you use, etc.