how to remove argument labels from polar plot in MATLAB - matlab

Does anyone know a simple way to remove the labels from the argument axis in a polar plot in MATLAB? My figures are small and I have to zoom in to see them, but when I do this the argument labels from one subplot get in the way of the other subplots.
Equally, if anyone knows of a way to solve this issue by rescaling the axis in the radial direction, or of any solution for that matter, then I would be very grateful. For the mean time I'll have to trim and re-size in Latex.
I tried the method here
How to remove Rho labels from Matlab polar plot?
but it didn't work.
here is some sample code
subplot(1,3,1,'align');
r = 10;
polar(t,abs((r.*exp(t.*1i) - (1+1i)).^2));
set(gca, 'fontsize', 20)
set(findall(gca, 'String', '0'),'String', ' ') %remove theta labels
hold on

Given the following example input:
t = 0:.01:2*pi;
polar(t,sin(2*t).*cos(2*t),'--r')
You can remove the vertical labels (along rho) by keeping only the legit ones.
% Find all handles to text labels
h = findall(gca,'type','text');
% Define what to keep
legit = {'0','30','60','90','120','150','180','210','240','270','300','330','360',''};
% Take the others and set them to empty string
idx = ~ismember(get(h,'string'),legit);
set(h(idx),'string','')
EDIT addressing comments
One approach would be simply setting to empty string '' those labels defined IN legit, i.e. by removing ~ near ismember. However, this approach is not robust in the sense that it will remove all of the labels that match. Suppose you have some other label with 120, then it will be removed as well.
One way to solve this issue is to edit polar() on line 155 and 162 by adding a 'Tag' to the radial annotations:
'HandleVisibility', 'off', 'Parent', cax,'Tag','spoke');
Then, save the edited function, plot, retrieve those text labels, and set to empty string:
h = findall(gca,'Type','text','-and','Tag','spoke');
set(h,'string','')

Related

Removing scientific notation in plot axis (Matlab) [duplicate]

Tick labels for ticks bigger than about 10'000, get formatted to 1x10^4 for example. Whereas the exponential part appears above the corresponding axes. This misbehavior has been well described on on matlab central as well, but without a solution.
Thanks for your help.
The 'quick trick'
set(gca, 'YTickLabel',get(gca,'YTick'))
did not work when applied to bar3, as can be seen on the following figure.
EDIT
According to this technical solution page, the recommended way of formatting the tick labels is this (you can use any of the number formatting functions like NUM2STR, SPRINTF, MAT2STR, or any other..)
y = cool(7);
bar(y(:,1)*1e6)
set(gca, 'YTickMode','manual')
set(gca, 'YTickLabel',num2str(get(gca,'YTick')'))
However there seems to be a bug when it comes to the Z-axis (the labels are correctly formatted, but the exponential multiplier is still showing for some reason!)
y = cool(7);
bar3(y*1e6, 'detached')
set(gca, 'ZTickMode','manual')
set(gca, 'ZTickLabel',num2str(get(gca,'ZTick')'))
Finally, there's another workaround where we replace the tick labels with text objects (see this technical solution page as reference):
y = cool(7);
bar3(y*1e6, 'detached')
offset = 0.25; Xl=get(gca,'XLim'); Yl=get(gca,'YLim'); Zt=get(gca,'ZTick');
t = text(Xl(ones(size(Zt))),Yl(ones(size(Zt)))-offset,Zt, num2str(Zt')); %#'
set(t, 'HorizontalAlignment','right', 'VerticalAlignment','Middle')
set(gca, 'ZTickLabel','')
One other trick you can try is to scale your data before you plot it, then scale the tick labels to make it appear that it is plotted on a different scale. You can use the function LOG10 to help you automatically compute an appropriate scale factor based on your plotted values. Assuming you have your data in variables x and y, you can try this:
scale = 10^floor(log10(max(y))); %# Compute a scaling factor
plot(x,y./scale); %# Plot the scaled data
yTicks = get(gca,'YTick'); %# Get the current tick values
set(gca,'YTickLabel',num2str(scale.*yTicks(:),'%.2f')); %# Change the labels
One way to get better control over tick labels, and to avoid the exponential formatting, is to use TICK2TEXT from the File Exchange.
Here's an example:
y = cool(7); %# define some data
ah = axes; %# create new axes and remember handle
bar3(ah,y*1E6,'detached'); %# create a 3D bar plot
tick2text(ah, 'ztickoffset' ,-1.15,'zformat', '%5.0f', 'axis','z') %# fix the tick labels

Customized Legend in Matlab

Here I have a for loop to plot the content of my matrix.
Based on 'type' value I determine the plot object (ks,bO,rX)
for k = 1:length(data1)
if(type(k)==1)
h=plot(data1(k,1),data1(k,2),'ks');set(h,'linewidth',2);hold on;
elseif(type(k) ==0)
h=plot(data1(k,1),data1(k,2),'bO');set(h,'linewidth',2); hold on;
else
h=plot(data1(k,1),data1(k,2),'rX');set(h,'linewidth',2); hold on;
end
end
I am little bit confused to find a way to put legend in my final figure, which shows my own explanation regarding each object(ks,bO,rX).
By default, MATLAB will see the output of this loop as not three plots but as many individual plotted points. Even though some of the points are plotted with the same settings, it doesn't automatically recognise them as part of the same series. If you give it three legend entries, it will assign them to whatever the first three points plotted were.
The simplest way around this is to change the way you plot and use logical indexing, rather than a loop:
h=plot(data1(type==1,1),data1(type==1,2),'ks'); set(h,'linewidth',2);
hold on;
h=plot(data1(type==0,1),data1(type==0,2),'bO'); set(h,'linewidth',2);
h=plot(data1(type==-1,1),data1(type==-1,2),'rX'); set(h,'linewidth',2);
Now we have only three plots, so giving legend the three should give us the correct match between those plots (in the order they were plotted) and our labels:
legend({'Type 1'; 'Type 0' ; 'Type -1'})

How to specify the axis size when plotting figures in Matlab?

Suppose that I have 2 figures in MATLAB both of which plot data of size (512x512), however one figure is being plotted by an external program which is sets the axis parameters. The other is being plotted by me (using imagesc). Currently the figures, or rather, the axes are different sizes and my question is, how do I make them equal?.
The reason for my question, is that I would like to export them to pdf format for inclusion in a latex document, and I would like to have them be the same size without further processing.
Thanks in Advance, N
Edit: link to figures
figure 1: (big)
link to smaller figure (i.e. the one whose properties I would like to copy and apply to figure 1)
For this purpose use linkaxes():
% Load some data included with MATLAB
load clown
% Plot a histogram in the first subplot
figure
ax(1) = subplot(211);
hist(X(:),100)
% Create second subplot
ax(2) = subplot(212);
Now link the axes of the two subplots:
linkaxes(ax)
By plotting on the second subplot, the first one will adapt
imagesc(X)
First, you have the following:
Then:
Extending the example to images only:
load clown
figure
imagesc(X)
h(1) = gca;
I = imread('eight.tif');
figure
imagesc(I)
h(2) = gca;
Note that the configurations of the the first handle prevail:
linkaxes(h)
1.Get the handle of your figure and the axes, like this:
%perhaps the easiest way, if you have just this one figure:
myFigHandle=gcf;
myAxHandle=gca;
%if not possible, you have to search for the handles:
myFigHandle=findobj('PropertyName',PropertyValue,...)
%you have to know some property to identify it of course...
%same for the axes!
2.Set the properties, like this:
%set units to pixels (or whatever you prefer to make it easier to compare to the other plot)
set(myFigHandle, 'Units','pixels')
set(myAxHandle, 'Units','pixels')
%set the size:
set(myFigHandle,'Position',[x_0 y_0 width height]) %coordinates on screen!
%set the size of the axes:
set(myAxHandle,'Position',[x_0 y_0 width height]) %coordinates within the figure!
Ok, based on the answer of #Lucius Domitius Ahenoba here is what I came up with:
hgload('fig1.fig'); % figure whose axis properties I would like to copy
hgload('fig2.fig');
figHandles = get(0,'Children');
figHandles = sort(figHandles,1);
ax(1) = findobj(figHandles(1),'type','axes','-not','Tag','legend','-not','Tag','Colorbar');
ax(2) = findobj(figHandles(2),'type','axes','-not','Tag','legend','-not','Tag','Colorbar');
screen_pos1 = get(figHandles(1),'Position');
axis_pos1 = get(ax(1),'Position');
set(figHandles(2),'Position',screen_pos1);
set(ax(2),'Position',axis_pos1);
This is the 'before' result:
and this is the 'after' result:
Almost correct, except that the aspect ratios are still off. Does anybody know how to equalize everything related to the axes? (I realize that I'm not supposed to ask questions when posting answers, however adding the above as a comment was proving a little unwieldy!)

MATLAB - How to zoom subplots together?

I have multiple subplots in one figure. The X axis of each plot is the same variable (time). The Y axis on each plot is different (both in what it represents and the magnitude of the data).
I would like a way to zoom in on the time scale on all plots simultaneously. Ideally by using the rectangle zoom tool on one of the plots, and having the other plots change their X limits accordingly. The Y limits should remained unchanged for all of this. Auto fitting the data to fill the plot in the Y direction is acceptable.
(This question is almost identical to Stack Overflow question one Matplotlib/Pyplot: How to zoom subplots together? (except for MATLAB))
Use the built-in linkaxes function as follows:
linkaxes([hAxes1,hAxes2,hAxes3], 'x');
For more advanced linking (not just the x or y axes), use the built-in linkprop function
Use linkaxes as Yair and Amro already suggested. Following is a quick example for your case
ha(1) = subplot(2,1,1); % get the axes handle when you create the subplot
plot([1:10]); % Plot random stuff here as an example
ha(2) = subplot(2,1,2); % get the axes handle when you create the subplot
plot([1:10]+10); % Plot random stuff here as an example
linkaxes(ha, 'x'); % Link all axes in x
You should be able to zoom in all the subplots simultaneously
If there are many subplots, and collecting their axes handle one by one does not seem a clever way to do the job, you can find all the axes handle in the given figure handle by the following commands
figure_handle = figure;
subplot(2,1,1);
plot([1:10]);
subplot(2,1,2);
plot([1:10]+10);
% find all axes handle of type 'axes' and empty tag
all_ha = findobj( figure_handle, 'type', 'axes', 'tag', '' );
linkaxes( all_ha, 'x' );
The first line finds all the objects under figure_handle of type "axes" and empty tag (''). The condition of the empty tag is to exclude the axe handles of legends, whose tag will be legend.
There might be other axes objects in your figure if it's more than just a simple plot. In such case, you need to add more conditions to identify the axes handles of the plots you are interested in.
To link a pair of figures with linkaxes use:
figure;imagesc(data1);
f1h=findobj(gcf,,’type’,’axes’)
figure;imagesc(data2);
f2h=findobj(gcf,,’type’,’axes’)
linkaxes([f1h,f2h],’xy’)

How do I visualize a matrix with colors and values displayed?

I want to create images like this from a double precision matrix using MATLAB.
Sample image:
http://twitpic.com/2xs943
You can create this sort of plot yourself pretty easily using the built-in functions imagesc and text and adjusting a number of parameters for the graphics objects. Here's an example:
mat = rand(5); % A 5-by-5 matrix of random values from 0 to 1
imagesc(mat); % Create a colored plot of the matrix values
colormap(flipud(gray)); % Change the colormap to gray (so higher values are
% black and lower values are white)
textStrings = num2str(mat(:), '%0.2f'); % Create strings from the matrix values
textStrings = strtrim(cellstr(textStrings)); % Remove any space padding
[x, y] = meshgrid(1:5); % Create x and y coordinates for the strings
hStrings = text(x(:), y(:), textStrings(:), ... % Plot the strings
'HorizontalAlignment', 'center');
midValue = mean(get(gca, 'CLim')); % Get the middle value of the color range
textColors = repmat(mat(:) > midValue, 1, 3); % Choose white or black for the
% text color of the strings so
% they can be easily seen over
% the background color
set(hStrings, {'Color'}, num2cell(textColors, 2)); % Change the text colors
set(gca, 'XTick', 1:5, ... % Change the axes tick marks
'XTickLabel', {'A', 'B', 'C', 'D', 'E'}, ... % and tick labels
'YTick', 1:5, ...
'YTickLabel', {'A', 'B', 'C', 'D', 'E'}, ...
'TickLength', [0 0]);
And here's the figure this generates:
If you run into trouble with the x-axis tick labels you choose being too wide and overlapping one another, here's how you can handle it:
Newer versions of MATLAB: Not sure which version this was added, but in newer versions axes objects now have the properties '{X|Y|Z}TickLabelRotation', which allow you to rotate the labels and fit them better.
Older versions of MATLAB: For older versions you can find some submissions on the MathWorks File Exchange that can rotate the tick label text, like XTICKLABEL_ROTATE from Brian Katz.
h = imagesc(magic(8))
impixelregion(h)
http://www.mathworks.com/help/toolbox/images/ref/impixelregion.html
Requires Image Processing Toolbox
If you only care about looking at zero/non-zero entries in your matrix (e.g. if it's sparse), use spy.
Else, use imagesc.
PS: I can't access your image
I expect you could persuade Matlab to draw that, if you look at the File Exchange you may find someone has already written the code. But it would be a lot easier, if you don't have the code, to use MS Excel.
EDIT: So I gave this some more thought and here's what I came up with. I've not mastered posting graphics to SO, so trust me, this will lead you towards a solution. But it would honestly be easier with Excel.
First define a matrix with your data values; I call the matrix G in the following. Then execute the commands:
image(G);
colormap(gray)
Now, I had to do some fiddling around, rescaling the data, to get a good graphic, but this should produce a gray-scale plot with numeric axes. Now, go to your figure window and open the plot tools.
Select the X axis and hit the Ticks button. All you have to do now is edit the labels to the texts that you want. Do the same for the Y axis. Write the numbers in the squares on the plot -- use the Text Box from the Annotations menu.
After a lot of fiddling about you'll have the graphic you want. At this point, I suggest that you choose the menu command File | Generate M-File and do just that. If you want to create such graphics programmatically in future just turn the generated M file into a proper function that does what you want.
But it's still a lot easier in Excel.