Matlab - Move Y-Axis to origin? - matlab

I know that Matlab sometimes isn't the best tool to create "fancy" plots but since my university requires it I dont have much choice.
I want to move the Y-Axis and the "arrow"-Annotation of the following example to x=0.
X = -pi/2 : 0.001 : pi/2;
Y = cos(X).^2;
plot(X, Y,'Color',[0,0,1]);
ylim([0 1.2]);
set(gca, 'YTick',[1.2],'yticklabel',{'{\color[rgb]{0,0,1}X(f)}'});
set(gca, 'XTick',[-pi/2,pi/2],'xticklabel',{'-f_{max}' 'f_{max}'});
set(gca,'fontsize',16);
box off;
grid off;
fig_pos=get(gca,'Position');
xp1=fig_pos(1);
xp2=fig_pos(1)+fig_pos(3)+0.02;
yp1=fig_pos(2);
yp2=fig_pos(2)+fig_pos(4)+0.03;
a1=annotation('arrow', [xp1 xp2],[yp1 yp1]);
a2=annotation('arrow', [xp1 xp1],[yp1 yp2]);
I tried to use PlotAxesAtOrigin and axescenter of the FileExchange but due to the annotations this doesn't work properly.
Does anyone know a way to make this work?
Thanks for your help, Klaus!

Moving the y-axis arrow annotation is straight forward. Simply replace your last line with
a2=annotation('arrow', fig_pos(1)+fig_pos(3)/2*[1 1],[yp1 yp2]);
Moving the X(f) is slightly more problematic as you can no longer use the Ytick labels.
Replace your 5th line with
set(gca, 'YTick','');
and add the following line
text(0.1,1.2,'{\color[rgb]{0,0,1}X(f)}','FontSize',16);
at the end of the code.
There's no way to remove the black vertical line that is still on the left side of the axes, so you need to mask it with another annotation. Something like
annotation('line',fig_pos(1)*[1 1],[fig_pos(2) fig_pos(2)+fig_pos(4)],...
'Color',get(gcf,'Color'),'LineWidth',2);
would do.
That gives
A final note is that you create a variable called fig_pos. That is misleading as it contains the axis position (on the figure), not the figure position (which is its position relative to the lower left corner of your monitor). Your variable should really be called axis_pos.

You can use "axis" command, if you know the value of fmax. axis([xmin xmax ymin ymax])

Related

Axis commands changes TightInset property to zero

I use some things from this question get-rid-of-the-white-space-around-matlab-figures-pdf-output to get rid of the white space when saving figure plots and images. This works fine, but my problem is when I use commands like "axis square" or "axis image". Ivt sets TightInset property of corresponding axes to 0 in "y" direction. I mean when I use this:
inset=get(a,'TightInset');
second and fourth numbers in "inset" are always zero, even if I set title and x-label. So in the end I don't see plot titles and x-labels.
Can I fix it somehow? So far I do it manually by adding some suitable number, but it is not convenient.
EDIT: Some more code for example. It displays two histograms.
h=figure;
subplot(121)
bar(bins,histogram1,'hist');
axis square
title('Historgram 1');
xlabel('Intensity');
ylabel('Pixel count');
set(gca,'xlim',[0 1])
subplot(122)
bar(bins,histogram_out,'hist');
axis square
title('Histogram 2');
set(gca,'xlim',[0 1])
xlabel('Intensity');
ylabel('Pixel count');
and if I call
a=get(h,'Children');
for i=1:length(a)
inset=get(a(i),'TightInset');
%...some stuff here
end
those y-related numbers in inset are zeros. If I comment axis square and do this, then inset are correct and it does what I need.
As far as I know when you use 'TightInset' you'll get only the graph or image, axis will be removed. I downloaded a function from mathworks file exchange 'saveTightfigure.m' to solve a similar problem. But I did not needed axes. If you need axes may be you can edit limits set inside the function. I mean you can give a little more space at left and bottom for keeping the axes.

matlab: plot area continues after data ends

I have a simple plot in Matlab but as you can see from the screenshot. There is a lot of white space on the right side of the graph after the end of the data series.
Any idea how to get rid of this white space and make the plot go right to the edge of the figure? Here is my code:
Plotx = plot(x);
hold on
PlotState = plot(Y);
set(Plotx,'Color','black','LineWidth',2.5);
set(PlotState,'Color','red','LineWidth',2.5);
set(gca, 'XTick',(1:3:62))
labels = time;
set(gca,'XTickLabel',labels(1:3:62))
grid on
This usually works for me:
axis tight;
xlim('auto');
You must select your figure, go back to the console and use those commands so they affect the last active figure.
EDIT: The above line should automatically make your graph axis very tight on your data. For more fine control, you may want to define the axis limits manually:
axis([xmin,xmax,ymin,ymax])
I found a solution. I manually adjust the limit of the x-axis, using:
set(gca,'XLim',[0 63])

double axis used in matlab

I am using a plotyy in matlab to plot two data set in a same figure. The left and right axis are of the different range. But I just find that on the right axis, there seems to be two different set of scale shown. I think one of them is really from the left axis.
t=-1:0.02:1;
y=sin(t);
y1=2*sech(t);
[AX, H] =plotyy(t, y, t, y1);
ylim(AX(2), [0 3.25]);
set(AX(2), 'YTickMode', 'auto')
After searching that online, I found that to turn off the box will solve the problem too. But the problem is to turn the box off will case the top horizontal line gone also. Is that anyway to remove the extra scale and keep the frame? Thanks.
It is possible and not terribly difficult, here's an illustrative example figure based on your test code
What I've done is to add a third axis (in this case I accomplished this by taking a shortcut - I called plotyy twice resulting in an extra blue line in the first axis and an extra second axis with a green line).
The idea is to turn the bounding box off for both the first and second axes, and then to turn it on for the third. That results in the top axis giving you the left vertical axis, the second the right vertical axis, and the third the top horizontal axis.
I don't think there's simple a way to do what you want. If you turn off the box (to get rid of the blue ticks on the right hand side) then the top horizontal line will disappear:
set(AX(1), 'Box','off')
If you want you could re-draw the line back in with:
line([-1, 1], [1, 1])
Or more generally:
lims = get(AX(1),{'XLim','YLim'});
line(lims{1}, lims{2}([2 2]))

Remove border around Matlab plot

Matlab is displaying a black border around a plot and I would like to remove it. I think i should be using something like:
set(Figure#,'PropertyName',PropertyValue);
But I'm not sure what PropertyName or PropertyValue should be used...
Edit:
I tried all of the suggestions including:
set(gca,'box','off');
set(gca,'xcolor','w','ycolor','w','xtick',[],'ytick',[]);
axis off;
The figure still has a black boarder and looks like this:
Edit 2:
This is a simplified package that reproduces the black box. Run the script called "runPlot". Here it is:
http://dl.dropbox.com/u/8058705/plotTest.zip
I can't figure out why the box is still visible. This might be due to the line in "plotTEC.m"
axis([-.65 .6 .25 1.32]) % hardwiring axis length since the coastline runs off of the plot
#Pursuit: If I use "plot browser" I get a recursive error....I am not familiar with the matlab plotting package but this seems strange. Does anyone else get this error? Again, thank you guys for your advise!
Does anyone have any other suggestions?
Thanks in advance!
You want to experiment with the properties of the axis. Some properties of interest.
xcolor %The color of the x-axis line and the x axis labels
ycolor %
box %'on', or 'off' indicating if one or both sides of a plot should have lines
xtick %Where to place the labels
ytick
For a completely bare plot, use:
figure
set(gca,'xcolor','w','ycolor','w','xtick',[],'ytick',[])
To set the figure background to white as well
set(gcf,'color','w')
Depending on your exact problem, you can try the 'box' property, to see how it affects your plots
set(gca,'box','on')
set(gca,'box','off')
If you want to turn off the actual plots lines but keep the plot labels then I am not aware of a simple solution. I think that I would need to remove the axes as described above, and then manually add labels using the text function.
Edit: As I just learned from this question, Plot Overlay MATLAB you can also try
axis off
axis on
Which I think is equivalent to
set(gca,'visible','off')
set(gca,'visible','on')
Edit 2:
If nothing else works, activate the "plot browser" in your figure. Use "view" --> "plot browser". From the plot browser panel, uncheck each object until you figure out which object is drawing the lines that you need to remove.
Then double click on the offending object to bring up the "property editor" panel, and mostly likely click "More properties" to view all possible properties of that object. From that view you can (hopefully) figure out what object is drawing the offending lines.
After you have figured out the object and property to edit, you can probably figure out where in the code that object is created, and set the property programmatically.
Try:
set(gca, 'Box', 'off');
Solution to remove 'gray' background in imagesc
I = imread('imgname.jpg');
[rows columns] = size(I);
posX = 100; posY = 100; %you can set any value for posX and posY - try to keep it on screen
f = figure (1);
imagesc(I);
set(gcf,'Position',[posX posY columns rows]);
set(gca,'units','pixels');
set(gca,'units','normalized','position',[0 0 1 1]);
axis off;
axis tight;
This should save the image with same size as that of the original, using imagesc.
Cheers!
set( gca , 'Visible' , 'off' );

Turning y axis upside down in MATLAB

Is there a way to turn the y axis upside down in matlab plots, so that the positive direction of the y axis, instead of up, points down ?
(I beg of you; please do not say, print it out, then turn the paper around ;-)
The 'YDir' axes property can be either 'normal' or 'reverse'. By default it is 'normal' for most plots, but some plots will automatically change it to 'reverse', such as the image or imagesc functions.
You can set the y-axis direction of an axes with either the set function or dot indexing (in newer MATLAB versions):
h = gca; % Handle to currently active axes
set(h, 'YDir', 'reverse');
% or...
h.YDir = 'reverse';
I'm baffled by some of the other answers saying that the 'YDir' property has somehow disappeared or is giving an error. I haven't seen any such behavior in versions of MATLAB from 2013, 2014, or 2016. There are only two potential pitfalls I came across:
The property can't be set with a cell array, only a character string:
>> set(gca, 'YDir', {'reverse'});
Error using matlab.graphics.axis.Axes/set
While setting property 'YDir' of class 'Axes':
Invalid enum value. Use one of these values: 'normal' | 'reverse'.
although this works:
set(gca, {'YDir'}, {'reverse'}); % Property name is also a cell array
The gca function can't be used interchangeably as a handle when performing dot indexing (which is why I first saved it to a variable h in the above example):
>> gca.YDir
Undefined variable "gca" or class "gca.YDir".
>> gca.YDir = 'reverse' % Creates a variable that shadows the gca function
gca =
struct with fields:
YDir: 'reverse'
Finally, if you want some code that will toggle the 'YDir' property no matter what its current state is, you can do this:
set(gca, 'YDir', char(setdiff({'normal', 'reverse'}, get(gca, 'YDir'))));
% or...
h = gca;
h.YDir = char(setdiff({'normal', 'reverse'}, h.YDir));
The command
axis ij
Will also reverse the Y-axis (negative above x-axis; positive below).
The solutions on the top of the stack did not work for me,
imagesc(x,y,data) % results in a flipped plot, the y axis is upside down
set(gca,'YDir','reverse'); % gives an error
axis ij; % still gives the flipped plot
what did work was the following:
imagesc(x,y,data); axis xy; % results in the correct plot
The YDir property has vanished in the matlab version (2013 and up) that I'm using.
To update this answer, since it is still a popular Google result:
As of R2014a, the correct way to flip the Y axis is the following:
>> axis ij
This change can be reversed through the following command
>> axis ji
To flip the X or Z axes, do the following
set(gca,'XDir','reverse');
set(gca,'ZDir','reverse');
Personally, I think it would have been easier to keep the YDir option, but what do I know.
As an alternative to YDir (for some reason I cannot currently see) you can rotate the axes with view. To turn the y-axis upside down, use
view(0,-90);