MATLAB: How to set a scale in a figure (similiar to Google Maps)

figurer2019bscalezoom in

Hi all,
I have the following set of data, time versus Intensity. When I plot them want to draw a scale that changes accordingly with the zoom. I want to start with a default scale of 10 second. At the moment I zoom-in the figure, I want the scale to be shorter (something like Google Maps), for example, from 10 seconds to 1 second, and 0.05 second. Also, I want the scale be fixed to the figure. Therefore, I can pan the data and match the scale to the spikes you see in the figure. I have been using a line to check the baseline drift. The line is fixed to the figure, so I can pan the data and match the line to the beggining of the spike. I want to do the same with the scale (again, something similar to Google Mpas scale).

Best Answer

I don't understand what you're doing with that line to check baseline. I'll continue to read that however here is a quick scale bar that i'll let you adjust to stay locked to one of your scale bar sizes. This should get you going and you can adjust the scale plot color, shape etc, to get it how you'd like to see it. Especially adjusting the position within the frame
function Matlabanswer()
%gen dummy data
t=0:.001:10;
intensity = rand(size(t)).^2.*rand(size(t)).^10+rand(size(t)).^100;
hfig = figure(1);clf
hax(1) = axes(hfig);
plot(hax(1),t,intensity),xlabel('time'),ylabel('instensity');
ylim([0 20])
hax(2) = axes(hfig); %create the floating box where the scaler bar will be located
scalePos = [hax(1).Position(1)...
hax(1).Position(2)+hax(1).Position(4)-.1...
.1*hax(1).Position(3)...
.1*hax(1).Position(4)]; %designate upper left corner
%and scale secondary axes to be
%1/10 the size
hax(2).Position = scalePos; %scale the 2nd axes to the first.
plot(hax(2),t,zeros(size(t))) %plot data
xlim(hax(2),hax(1).XLim) %plot line the same length as data but in the 1/10 axes
set(hax(2),'XColor', 'none','YColor','none','color','none') %make scale axes invisible
%here is the section for annotation of what the scale line is
hanno = annotation('textbox', scalePos-[0 .05 0 0], 'String', ...
['scale ' num2str(.1*(diff(hax(1).XLim))) 'x']);
hanno.LineStyle='none';
%initiate the function for what happens when zooming
hzoom = zoom(hfig);
set(hzoom,'ActionPostCallback',{@myzoomfunction,hax,hanno});
function myzoomfunction(obj,event,AX,AnnoText)
xlim(AX(2),AX(1).XLim); %update the scale axes to match up with zoomed data
AnnoText.String=['scale ' num2str(.1*(diff(AX(1).XLim))) 'x']; %update the scale annotation