Plot hidden under another plot in Matlab - matlab

I am creating a candlestick chart representing stock prices. Once created, I want to add green circle showing where/when I am buying the stock.
hold on;
candle(myData.High, myData.Low, myData.Close, myData.Open, '', myData.Date, 'dd/mm/yy');
m = plot(myExecutionTable.BuyDate,myExecutionTable.BuyPrice,'og')
uistack(m)
hold off;
The problem is that if myExecutionTable.BuyPrice has a value between the Open and Close, the circle is not showing up. I guess it is hidden under the candlestick. Hence I tried to use uistack but without success. When I change to
plot(myExecutionTable.BuyDate,myExecutionTable.BuyPrice+100,'og')
the green circle then appears (above the candlestick)
Thanks,
Serge

The easiest way to make sure one graphics object is on top of another (and not below), is to plot it later.
If for some reason you can't do it this way, you can also manipulate the order of the child objects of the axes:
h = get(gca, 'Children');
returns a vector of graphics handles. Exchange handles between positions in this vector (higher index means higher on top), and then write it back using
set(gca, 'Children', h)

Related

How to update a scatter3 plot (in a loop) in Matlab

Quite a simple question but just couldn't find the answer online... I want to visualise a point cloud gathered from a lidar. I can plot the individual frames but wanted to loop them to create a "animation". I know how to do it for normal plots with drawnow but can't get it working with a scatter3. If I simply call scatter3 again like I have done in the commented code then the frame that I am viewing in the scatter plot jumps around with every update (Very uncomfortable). How do i get the scatter3 plot to update to the new points without changing the UI of the scatter ie. Still be able to pan and zoom around the visualised point cloud while it loops through.
EDIT: The file is a rosbag file, I cannot attach it because it is 170MB. The problem doesn't happen when using scatter3 in a loop with a normal array seems to be something with using scatter3 to call a PointCloud2 type file using frame = readMessages(rawBag, i).
EDIT: The problem does not seem to be with the axis limits but rather with the view of the axis within the figure window. When the scatter is initialised it is viewed with the positive x to the right side, positive y out of the screen and positive z upwards, as shown in view 1. Then after a short while it jumps to the second view, where the axis have changed, positive x is now out of the screen, positive y to the right and positive z upwards (both views shown in figures). This makes it not possible to view in a loop as it is constantly switching. So basically how to update the plot without calling scatter3(pointCloudData)?
rawBag = rosbag('jackwalking.bag');
frame = readMessages(rawBag, 1);
scatter3(frame{1});
hold on
for i = 1:length(readMessages(rawBag))
disp(i)
frame = readMessages(rawBag, i);
% UPDATE the 3D Scatter %
% drawnow does not work?
% Currently using:
scatter3(frame{1})
pause(.01)
end
The trick is to not use functions such as scatter or plot in an animation, but instead modify the data in the plot that is already there. These functions always reset axes properties, which is why you see the view reset. When modifying the existing plot, the axes are not affected.
The function scatter3 (as do all plotting functions) returns a handle to the graphics object that renders the plot. In the case of scatter3, this handle has three properties of interest here: XData, YData, and ZData. You can update these properties to change the location of the points:
N = 100;
data = randn(N,3) * 40;
h = scatter3(data(:,1),data(:,2),data(:,3));
for ii = 1:500
data = data + randn(N,3);
set(h,'XData',data(:,1),'YData',data(:,2),'ZData',data(:,3));
drawnow
pause(1/5)
end
The new data can be totally different too, it doesn't even need to contain the same number of points.
But when modifying these three properties, you will see the XLim, YLim and ZLim properties of the axes change. That is, the axes will rescale to accommodate all the data. If you need to prevent this, set the axes' XLimMode, YLimMode and ZLimMode to 'manual':
set(gca,'XLimMode','manual','YLimMode','manual','ZLimMode','manual')
When manually setting the limits, the limit mode is always set to manual.
As far as I understood what you describe as "plots jumpying around", the reason for this are the automatically adjusted x,y,z limits of the scatter3 plot. You can change the XLimMode, YLimMode, ZLimMode behaviour to manual to force the axis to stay fixed. You have to provide initial axes limits, though.
% Mock data, since you haven't provided a data sample
x = randn(200,50);
y = randn(200,50);
z = randn(200,50);
% Plot first frame before loop
HS = scatter3(x(:,1), y(:,1), z(:,1));
hold on
% Provide initial axes limits (adjust to your data)
xlim([-5,5])
ylim([-5,5])
zlim([-5,5])
% Set 'LimModes' to 'manual' to prevent auto resaling of the plot
set(gca, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual')
for i=2:len(x,2)
scatter3(x(:,i), y(:,i), z(:,i))
pause(1)
end
This yields an "animation" of plots, where you can pan and zoom into the data while continuous points are added in the loop

Place MATLAB legend such that it does not overlap on the plot

I am generating multiple plots of different datasets in succession using MATLAB. I would like the legend positions to be such that they don't overlap on the plotted lines and it would be ideal if this placement could be done automatically.
I am aware of setting the 'Location' to 'best' to achieve this but the placement of the legend tends to be awkward when 'best' is used (below). Also, I would like the legend to be inside the plot. I also came across a way to make the legend transparent (here) so that it does not render the plotted data invisible, but explicitly placing the legend elsewhere is what I am looking for.
Is there a way to place the legend at the extremes of the image ('NorthWest', 'SouthWest' etc) automatically such that it does not overlap on the plotted data (apart from the methods suggested above)?
So, you have tried using Location instead of Position? For example:
x =1:100;
y = x.^2;
lgd = legend('y = x.^2');
set(lgd,'Location','best')
and you are getting odd results correct? A quick way of solving this would be to still use Location, with best, and extract the coordinates:
lgd.Position
You should get something like this:
ans =
0.7734 0.3037 0.1082 0.0200
which maps to:
[left bottom width height]
You will need to focus on left and bottom. These two values, left and bottom, specify the distance from the lower left corner of the figure to the lower left corner of the legend, and they are analogous to the grid frame you are using.
Then, depending on the size of the frame (I would suggest you use axis([XMIN XMAX YMIN YMAX]) for this, if possible), you can pinpoint the position of the legend within the grid. What you can do next, is check if and which of your graphs in the plot cross paths with the legend (maybe define a relative distance function based on some distance threshold) and if they do, then randomly reposition the legend (i.e. change the values of left and bottom) and repeat until your conditions are met.
If this still troubles you I can write a short snippet. Finally, know that you can always opt for placing the legend on the outside:
set(lgd,'Location','BestOutside')

Set plot (axes) view "box" without affecting limits

I have a 2D plot with many data elements on it covering a extensive area. Although all the data is necessary, I am usually interested on a small element of the plot.
I would like to programmatically focus the view on that element of interest, while allowing to use the zoom tool ((-) in the GUI) to fastly go back to a wider perspective.
It is easy to use set(gca, 'xlim', [limitsXOfSmallElement]) and set(gca, 'ylim', [limitsYOfSmallElement]) to set axis limits so that the small element is in focus, but this makes impossible to use the GUI (-) zoom tool to go back to the general view without manually resetting back axis limits to original values.
My intuition is that this could be solved by controlling camera properties (CameraPosition, CameraTarget and/or CameraViewAngle), but when I apply them, posterior uses of the GUI zoom tool have weird effects on the axis, as changing its position and size on the figure.
Is there a good method for setting the fragment of the 2D canvas that is displayed in the axis?
Consider the following example:
function example_zoom
%# some plot
plot(1:10)
hAx = gca;
%# save original axis limits
setappdata(hAx, 'limits',get(gca,{'XLim','YLim'}))
%# create custom toolbar button
[X,map] = imread(fullfile(toolboxdir('matlab'),'icons','view_zoom_out.gif'));
icon = ind2rgb(X,map);
uipushtool('CData',icon, 'ClickedCallback',{#click_cb,hAx});
%# zoom
uiwait(msgbox('Zooming now, click button to reset', 'modal'))
set(gca, 'XLim',[3 7], 'YLim',[2 9])
%zoom on
end
function click_cb(o,e, hAx)
%# restore original axis limits
limits = getappdata(hAx, 'limits');
set(hAx, 'XLim',limits{1}, 'YLim',limits{2})
end
The idea is to create your own toolbar button that restores the axis limits to their original values.

How do I hide axes and ticks in matlab without hiding everything else

I draw images to axes in my matlab UI, but I don't want the axes and ticks to be visible how do I prevent that, and also where do I make this call?
I do this
imagesc(myImage,'parent',handles.axesInGuide);
axis off;
Is this what you are looking for?
This is definitely somewhere else on this website and in the matlab documentation. Try typing
help plot
Or using the documentation on plotting!
edit: Now that you have shown what you are doing. (You don't need the handles, I just always write them in to clutter my workspace)
myImage = yurbuds0x2Dironman; # don't ask
fH = figure;
iH = imagesc(myImage);
set(gca,'xtick',[],'ytick',[])
Are you able to do it like this?
I support the
set(gca,'xtick',[],'ytick',[]);
approach over the
axis off
one. The reason is set(gca, ...) just removes the labels but keeps the axes, unlike axis off. I am generating a group of images with fixed dimensions to combine later into a video. Deleting the axes creates different size frames that can't be recombined.

Plot Overlay MATLAB

How do you take one plot and place it in the corner (or anywhere for that matter) of another plot in MATLAB?
I have logarithmic data that has a large white space in the upper right-hand side of the plot. In the white space I would like to overlay a smaller plot containing a zoomed in version of the log plot in that white space (sort of like a magnified view).
Before you tell me it can't be done, I would like to mention that I have seen it in action. If my description is lacking, just let me know and I'll attempt to better describe it to you.
An example:
x = 1:20;
y = randn(size(x));
plot(x, y,'LineWidth',2)
xlabel('x'), ylabel('y'), title('Plot Title')
h = axes('Position', [.15 .65 .2 .2], 'Layer','top');
bar(x,y), title('Bar Title')
axis(h, 'off', 'tight')
You can use axes properties 'position' and 'units' and make them overly. Pay attention to create small axes after big one or use uistack() function so that big does not hide small one.
What you can not do is to make an axes child of another one (like Mathworks do with legend). But you do not need it anyway.
For the second plot you have to use axes and line instead of plot and hold on.
Units as 'normalized' (which is default) allows uniform resizable look when parent figure is being resized (e.g. manually maximized).