matlab: making an areaseries transparent disrupts subplots - matlab

I'm trying to make the red bands in the second subplot of the figure below go transparent with an opacity similar to alpha(0.2).
http://i.stack.imgur.com/zJjYk.jpg
However, when I try to call alpha(0.2) after the following code that generates the red bands:
Plotha1 = area([datenum(time(11,1),1,1) datenum(time(15,1),1,1)],[1.3*max(SA(:,2)) 1.3*max(SA(:,2))]);
set(Plotha1,'BaseValue',1.3*min(SA(:,2)),'FaceColor','r','LineStyle', 'none');
Plotha2 = area([datenum(time(4,1),1,1) datenum(time(8,1),1,1)],[1.3*max(SA(:,2)) 1.3*max(SA(:,2))]);
set(Plotha2,'BaseValue',1.3*min(SA(:,2)),'FaceColor','r','LineStyle', 'none');
alpha(0.2);
The third subplot goes blank like in the second figure.
http://i.stack.imgur.com/tjgIT.jpg
The code generating the third subplot comes last in my code:
subplot(3,1,3),
W = zeros(T,1);
PlotZeros = plot(datenum(time,1,1),W);
dateFormat = 'yyyy';
datetick('x',dateFormat);
hold on
PlotResid = plot(datenum(time,1,1),Resid);
set(PlotZeros,'Color',[0.5 0.5 0.5]); %grey
set(PlotResid,'Color','blue');
axis([datenum(time(1,1),1,1) datenum(time(end,1),1,1) 1.3*min(Resid) 1.3*max(Resid)])
hold off
I have tried moving things around so that the code generating the 2nd subplot comes last but it still causes the 3rd subplot to go blank. Does anyone know how to make these areaseries red bands go transparent without disrupting the 3rd subplot?
Thanks!

You could try using fill or patch with the 'facealpha' property instead of the area command:
% x and y vals define the 4 corners of the rectangle
% (slightly different than "area")
x_vals=[datenum(time(4,1),1,1) datenum(time(8,1),1,1) ...
datenum(time(8,1),1,1) datenum(time(4,1),1,1)];
y_vals=[1.3*min(SA(:,2)) 1.3*min(SA(:,2)) ...
1.3*max(SA(:,2)) 1.3*max(SA(:,2))];
Plotha2 = fill(x_vals,y_vals,'red','edgecolor','none','facealpha',0.2);

Related

Matlab second y-axis label does not have the same "padding" as the first

I made a plot and wanted to add a second y-axis with different units of measurement.
Here is what I did:
...
...
plot(x,y,x,y1,x,y2)
ax1=gca;
set(gca,'YTickLabel',num2str(get(gca,'YTick').'))
legend('0.5 atm','1 atm','2 atm','Location','best')
title('H_2S equilibrium partial pressure for different total pressures')
xlabel('Temperature (K)')
ylabel('Partial pressure (Pa)')
hold on
ax2 = axes('Position',ax1.Position,...
'YAxisLocation','right',...
'Color','none');
ax2.YLim = [0 0.25];
ax2.XTick = [];
ylabel(ax2,'Partial pressure (atm)') % label right y-axis
Here is the result:
How do I get the right label to have the same padding between itself and the edge of the figure as the left label and border?
(view the picture on a dark background to see what I mean)
I've just discovered export_fig.
It automatically crops extra space from plots and also adds nifty features, such as anti-aliasing!

Simultaneous interaction with 2 figures in MATLAB GUI

I am writing a GUI in MATLAB (guide) where user will be shown 2 images(both images are positioned side by side in single gui window) from a series of images (but each drifted little bit) and will be allowed to select area of interest.
I want user to select working are in image 1 while simultaneously highlighting the selected area in image 2, so that it is easier to judge whether the feature of interest has drifted out of selected area or not. How to do that?
I am using following answer to select and crop area of interest(just FYI):
crop image with fixed x/y ratio
Here is a way to do it using imrect and its addNewPositionCallback method. Check here for a list of available methods.
In the following figure I create 2 axes. On the left that's the original image and on the right that's the "modified" image. By pressing the pushbutton, imrect is called and the addNewPositionCallback method executes a function, called GetROIPosition that is used to get the position of the rectangle defined by imrect. At the same time, in the 2nd axes, a rectangle is drawn with the same position as that in the 1st axes. To be even more fancy you can use the setConstrainedPosition to force the rectangle to be enclosed in a given axes. I'll let you do it :)
Here is the whole code with 2 screenshots:
function SelectROIs(~)
%clc
clear
close all
%//=========================
%// Create GUI components
hfigure = figure('Position',[300 300 900 600],'Units','Pixels');
handles.axesIm1 = axes('Units','Pixels','Position',[30,100,400 400],'XTick',[],'YTIck',[]);
handles.axesIm2 = axes('Units','Pixels','Position',[460,100,400,400],'XTick',[],'YTIck',[]);
handles.TextaxesIm1 = uicontrol('Style','Text','Position',[190 480 110 20],'String','Original image','FontSize',14);
handles.TextaxesIm2 = uicontrol('Style','Text','Position',[620 480 110 20],'String','Modified image','FontSize',14);
%// Create pushbutton and its callback
handles.SelectROIColoring_pushbutton = uicontrol('Style','pushbutton','Position',[380 500 120 30],'String','Select ROI','FontSize',14,'Callback',#(s,e) SelectROIListCallback);
%// ================================
%/ Read image and create 2nd image by taking median filter
handles.Im = imread('coins.png');
[Height,Width,~] = size(handles.Im);
handles.ModifIm = medfilt2(handles.Im,[3 3]);
imshow(handles.Im,'InitialMagnification','fit','parent',handles.axesIm1);
imshow(handles.ModifIm,'InitialMagnification','fit','parent',handles.axesIm2);
guidata(hfigure,handles);
%%
%// Pushbutton's callback. Create a draggable rectangle in the 1st axes and
%a rectangle in the 2nd axes. Using the addNewPositionCallback method of
%imrect, you can get the position in real time and update that of the
%rectangle.
function SelectROIListCallback(~)
hfindROI = findobj(handles.axesIm1,'Type','imrect');
delete(hfindROI);
hROI = imrect(handles.axesIm1,[Width/4 Height/4 Width/2 Height/2]); % Arbitrary size for initial centered ROI.
axes(handles.axesIm2)
rectangle('Position',[Width/4 Height/4 Width/2 Height/2],'EdgeColor','y','LineWidth',2);
id = addNewPositionCallback(hROI,#(s,e) GetROIPosition(hROI));
end
%// Function to fetch current position of the moving rectangle.
function ROIPos = GetROIPosition(hROI)
ROIPos = round(getPosition(hROI));
axes(handles.axesIm2)
hRect = findobj('Type','rectangle');
delete(hRect)
rectangle('Position',ROIPos,'EdgeColor','y','LineWidth',2);
end
end
The figure after pressing the button:
And after moving the rectangle around:
Yay! Hope that helps! Nota that since you're using GUIDE the syntax of the callbacks will look a bit different but the idea is exactly the same.

Wrong 3D plot in Matlab

I'm trying to create 3D plots in Matlab, and I have practically no experience. I'd really like to draw the figure described by these equations:
x = cos(u) sinh(t) / (cosh(t) - cos(u));
y = cos(u) sin(u) / (cosh(t) - cos(u));
z = sin(u);
where both u and t vary from -pi to pi. This is what Paul Bourke calls Ghost Plane.
clc
clear
a = -pi:.01:pi;
b = -pi:.01:pi;
[U,T] = meshgrid(a,b);
X = (cos(U).*sinh(T))./(cosh(T)-cos(U));
Y = (cos(U).*sin(U))./(cosh(T)-cos(U));
Z = sin(U);
figure
surf(X,Y,Z)
With the code, I get something... indescribable. How do I plot the figure?
Your code is correct. You just need to zoom in.
Some tips to make this more viewable:
Use less fine grids, by changing a = ... and b = ... to: linspace(-pi,pi,40);
Add this ,'FaceColor','none','EdgeColor','interp'); to the surf command to only plot the lines and those in color.
Add this axis equal vis3d; after the surf command, so the axis will have correct scaling and behave well while rotating.
Add whitebg('black'); and grid off; to make the background black.
Change to surf(X,Y,Z,-U,...); and add colormap('HSV'); if you want the same colors as in the original.
set(gca,'xtick',[]); set(gca,'xticklabel',[]); set(gca,'yticklabel',[]); set(gca,'ytick',[]); to remove the axis ticks
You might want to use the cameratoolbar to: Change the projection to perspective projection, zoom all the way out, move the camera in very close, to get nice perspective distortions.
VoilĂ :

Why sometimes the bars with bar or hist have no border?

I noticed that sometimes, when I plot the bars using the functions bar() or hist(), the bars plotted have no border. They are a little bit less nice to see, and I would prefer the border or a little bit of space between them.
The figure shows what I got now, plotting three different datasets. The third graph is zoomed in order to show the lack of space between bars.
I get there this has something to do with the 'histc' parameters in bar function. Without the histc parameters the bars have some space between each others, but then the bar will be centered on the edges values, whereas I want the edges values to be, well, EDGES of each bar.
This is (the relevant part of) the code I used:
[...]
if edges==0
%these following lines are used to take the min and max of the three dataset
maxx=max(cellfun(#max, reshape(data,1,size(data,1)*size(data,2))));
minn=min(cellfun(#min, reshape(data,1,size(data,1)*size(data,2))));
edges=minn:binW:maxx+binW;
end
[...]
y{k}=histc(data{r,c}, edges);
bar(edges,y{k} , 'histc');
[...]
I think if you change the color of your bar plots you'll see that there actually is a border it just doesn't show up very well. You can also change the width of the bars so that they are more distinct.
% something to plot
data = 100*rand(1000,1);
edges = 1:100;
hData = histc(data,edges);
figure
subplot(2,1,1)
h1 = bar(edges,hData,'histc');
% change colors
set(h1,'FaceColor','m')
set(h1,'EdgeColor','b')
% Change width
subplot(2,1,2)
h1 = bar(edges,hData,0.4,'histc');
The EdgeColor and LineWidth properties of the Barseries object control the bar outlines. Try using the code and playing with the red, green, blue, and width values to get a better result.
red = 1;
green = 1;
blue = 1;
width = 3;
h = bar(edges,y{k} , 'histc');
set(h,'EdgeColor',[red green blue],'LineWidth',width);

Make background of annotation box in image semi-transparent

I am currently working on adding annotations to satellite images in MATLAB. Since the color underneath each text field can vary quite a lot, I want to use a background color under the text to make it easier to see and read.
However, when I do this, a lot of the terrain gets obscured. I though of trying to make the background color for each text box semi transparent, but hit a dead end trying to come up with a solution.
Any ideas? I was hoping for some UI-element where I could just set the 'facealpha' to maybe 0.5. I also need the text to support being rotated (as can be seen in the examples below).
Below is some example code and the resulting image. The workspace with the satellite data can also be found in the link:
Example workspace
figure(1);clf
imagesc(xx,yy,Map);
hold on
plot(xInspection,yInspection,'g.-')
% # Two ways of making a rotated text annotation.
% # Cant make background semi-transparent
testAnno= annotation('textarrow',[0.5 0.5],[0.5 0.5], ...
'string','textarrow annotation', ...
'HeadStyle','none','LineStyle', 'none',...
'TextRotation',asin(directionVec(1))*180/pi,...
'TextBackgroundColor',[0.7 0.7 0.7]);
testText = text(mean(xInspection),mean(yInspection),'text annotation', ...
'rotation',asin(directionVec(1))*180/pi, ...
'HorizontalAlignment','right', ...
'color',[0 0 0], ...
'backgroundcolor',[0.7 0.7 0.7], ...
'fontsize',8);
It doesn't look like either annotation or text return HgObjects that have BackgroundAlpha properties (they might exist but I wasn't able to find them using getundoc or by trying various different hacks).
I was able to get something working by drawing the background myself. Here is a simple proof of concept:
f = figure;
tObj = text(.5, .5, 'text object', 'FontSize', 20);
set(gca,'XLimMode', 'manual', 'YLimMode', 'manual'); % prevent the axes from resizing automatically
p = get(tObj, 'Extent'); %Get the outer position of the text
% now create a patch around the text object
pObj = patch([p(1) p(1) p(1)+p(3) p(1)+p(3)], [p(2) p(2)+p(4) p(2)+p(4) p(2)], 'r');
uistack(tObj, 'top'); % put the text object on top of the patch object
set(pObj , 'FaceAlpha', .2); % set the alpha of the patch face to .2
%Rotate the objects
set(tObj, 'Rotation', 20);
rotate(pObj, [0 0 1], 20);
I am afraid the only way you can do this is by not setting any color to your annotations, and then placing a patch in the background of each annotation. So something like this:
% Use completely transparent annotations
hA = annotation('textarrow', ..., 'TextBackgroundColor', 'none')
% Place a transparent patch exactly in the background of your annotation
hP = patch(X, Y, 'white', 'EdgeColor', 'none', 'FaceColor', 'white', ...
'alpha', 0.3)
% Ensure that your annotation is on top
uistack(hA, 'top')
But of course the big problem is to determine the correct coordinates of the patch (X and Y). Rotating is easy by simply multiplying your coordinates by a rotation matrix. However, finding the length and height of the patch and its central location is not that easy. You might be able to find some useful functions for this at Matlab central...