Is there a way to plot axis values with different (alternating) heights? - matlab

I like to plot in MATLAB a fourier-transformated signal.
Via set(gca,'xtick',peaks,'FontSize',12); i can show the peak values at the x-axis.
But sometimes, the peaks are too close together and the text showing the peak values is merging together with its neighbours. I have searched the web, but maybe asked the wrong question :)
So my question is:
How can i plot the peaks with alternating heights, like shown in the picture below?
I prefer the use of 1 x-axis.
Thank you for your help! :)

+1 for the interesting question.
Here's a way to do that, maybe not the most elegant, but shows the logic and make it happen:
x=0:pi/10:pi;
plot(x,sin(x));
set(gca, 'XTick', x, 'XTickLabel', cell(numel(x),1));
yl=get(gca,'YLim');
for n=1:numel(x)
if mod(n,2)
text(x(n), yl(1), {num2str(x(n)),''},'HorizontalAlignment','Center','VerticalAlignment','Top');
else
text(x(n), yl(1), {'',num2str(x(n))},'HorizontalAlignment','Center','VerticalAlignment','Top');
end
end
Use various text properties to change the font size, or text format etc...

Related

Why is line plot in subplot distorted when using barplot in other subplot

The upper subplot is a perfectly normal ECG signal.
The bottom subplot is a bar plot.
Only on windows matlab 2014a, the ECG signal gets screwed up. It seems like it groups data of when zooming in, it seems like the distance between peaks is the same as the width of a bar..
Nothing special happens in the code
why does this happen. both subplots should not even be aware of each other. seems like a bug to me..
figure;
subplot(211)
plot(decg.time,decg.values)
subplot(212)
h=bar(d.time,d.values)
If i understand correctly, the issue you are having is the uneven spacing between the bars in your bar plot; to fix this, i would try the following:
Set the 'barwidth' property to 1: bar(d.time, d.values, 'barwidth', 1)
change the renderer of the figure to painters: figure('renderer', 'painters');
In general, both bar and area plots tend to get "screwy" when having a large amount of data points, so resampling the data to a lower resolution might help. Also, the graphics engine has been updated in matlab 2015b, so simply updating might also help, if none of the above suggestions does.

Scatter with 2 y-axes and datetick

I would really appreciate some help.
I have to independent datasets. Each dataset contains two variables: dates (as datenumber) and corresponding data. I need to plot both datasets on one scatter plot with dates on x-axis and two y-axes. I have been trying with the following code:
figure(1);
scatter(x1,y1,'g');
set(gca);
ax1=gca;
set(ax1,'YColor','g');
ax2 = axes('Position',get(gca,'Position'),'YAxisLocation','right', XTick'[],'Color','none','YColor','r');
hold on; scatter(x2,y2,'r');
Now, this gives correct y-axis on the right side, however on the right side I end up with two overlapping y-axes.
Also, I need to change x-axis so that it displays dates as opposed to datenumbers. I've tried to incorporate datetick into the code but it again gives me two overlapping x-axes.
Does anyone know how to go about it?
thank you
I tried your script with your sample input and found no problems. Anyway, here's a solution which uses the matlab function plotyy, which is suited to simple plots like this:
%generate input
x1=[732490 732509 732512 732513 732521 732528];
y1=[7.828 7.609 22.422 14.758 26.258 1.477];
x2=[732402 732403 732404 732404 732433];
y2=[0.693 0.645 0.668 0.669 0.668];
figure(1);
[ax, h1,h2]=plotyy(x1,y1,x2,y2,'scatter');
%set colors manually
green=[0 1 0];
red=[1 0 0];
set(h1,'cdata',green);
set(h2,'cdata',red);
set(ax(1),'ycolor',green);
set(ax(2),'ycolor',red);
%note the 'keepticks' and 'keeplimits' options
datetick(ax(1),'x','yyyy-mm-dd','keepticks','keeplimits');
datetick(ax(2),'x','yyyy-mm-dd','keepticks','keeplimits');
Without the datetick call the plotyy function synchronizes the xticks in the plot. When you call datetick, it recalculates the ticks, unless you explicitly tell it not to, see the option keepticks, and this is seen as two sets of x axes (even though the x coordinates are the same, the ticks are located at different positions). The keeplimits option is needed to preserve the original xlim. It obviously needs some more manual work to get plots like this sufficiently pretty.
Also note that I set the axes and data colors manually: there might be a way to do this more elegantly.
Update: keeplimits originally missing
Update2: changed sample data to correspond to updated question comment

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.

Problem or bug in xticklabel_rotate while drawing heatmap and rotating xtick labels in Matlab

I have been drawing heatmaps with labels in Matlab, mainly using the functions imagesc to draw the heatmap and xticklabel_rotate to rotate the xtick labels.
(please see here for xticklabel_rotate).
It usually works well. But today I met some problem which appeared to be caused by xticklabel_rotate (or maybe the Matlab text handle used by xticklabel_rotate?)
To illustrate the problem, in the following I print my code and the results generated from the code (basically, what it does is to randomly generate a normally distributed data matrix, draw a heatmap for the data using imagesc, draw its labels on top and right of the axis, and then rotate xticklabels):
function debug_xticklabelRotate(numX, numY, axisFontsize)
data = randn(numY, numX);
imagesc(data);
colormap(jet);
box on
set(gca, 'ticklength', [0,0]);
set(gca, 'xminortick', 'off', 'yminortick', 'off');
set(gca, 'XAxisLocation', 'top');
set(gca, 'YAxisLocation', 'right');
set(gca,'FontSize', axisFontsize);
axis image
set(gca, 'Xtick', 1 : numX);
htext = xticklabel_rotate([],90, [], 'fontsize', axisFontsize);
set(gca, 'YTick', 1 : numY);
end
Problem 1: I called the above function with parameters as
debug_xticklabelRotate(40, 100, .5);
the output image is shown below (to save space here, I cut the image and only show the top few rows):
Please notice that the bug is that, as the result of calling xticklabel_rotate, neither the right side of the figure box nor the yticklabels are drawn.
Problem 2: When I call the above function with parameters as
debug_xticklabelRotate(40, 200, .5); % only numY is changed from 100 to 200
the output image is shown below (again to save space here, I cut the image and only show the top few rows):
http://i55.tinypic.com/317grdd.png
Compared to the call with numY=100, in this figure both the data image and the labels are shown. However, please notice two problems here. First, the fontsize of xticklabel is not the same as that of yticklabel (axisFontsize). Second, the xtick labels are not aligned well with the columns (xticks): some labels are closer and some are further away.
Please note if I remove the function call of xticklable_rotate in my function debug_xticklabelRotate, all these mentioned problems are gone (except that now the xticklabel are not rotated).
I wish my problem is stated clear above. Any suggestion on solving the problem will be highly appreciated. Thank you very much.
As the author of xticklabel_rotate, I have tried to reproduce the errors mentioned with only small success. I have found an issue with the axis position being changed when y-labels are on the right, which I will look into. I do not get such marked misalignements as you have shown when I run the same examples, so I am not sure how to respond. Please verify that these issues exist when you PRINT the figure, and it is not a simple display issue.
The text boxes are created at the tick positions, in data units. They are middle aligned, there is not much more that can be done, but I am open to suggestions.
PS. I agree it would be nice if this function was inherent in MatLab. If it was, I wouldn't have had to work on this.
If you comment out the line:
set(gca, 'YAxisLocation', 'right')
then it should work as expected. It seems that the XTICKLABEL_ROTATE function does not support right y-labels. You should contact the original author and let him know of the possible bug...

How to change the format of the numbers displayed on an axis in a MATLAB plot?

I actually have 3 questions:
I have a plot with data that is in the thousands and my plot's axis is diplaying the tick marks as .4 .8 1.0 1.2 and a *10^4 in the lower right. This is a little annoying.
Besides dividing my data by 1000 or hardcodig the tick marks is there a way to change to tick marks from .4*10^4 TO 4000?
Seems like this should be trivial but aftter browsing through all of the figure's properties I can't seem to get an where.
And...once I get 4000 to apear instead of .4*10^4 is there a way to rotate the tick mark label so it is not overlapping the other labels.
And..how do you set how many "major" tick marks there are?
Thanks so much!
ME
Try the following:
x=[4000, 8000, 10000, 12000]; % define the x values where you want to have a tick
set(gca,'XTick',x); % Apply the ticks to the current axes
set(gca,'XTickLabel', arrayfun(#(v) sprintf('%d',v), x, 'UniformOutput', false) ); % Define the tick labels based on the user-defined format
Reference: Mathworks
In regards to the label rotation, it seems that Matlab does not support such feature by its own, but someone wrote a script for the label rotation, and you might want to give it a try.
There's a nice function by Yair Altman called ticklabelformat to do that in case you want to still be able to freely play with the axes afterwards
description:
http://undocumentedmatlab.com/blog/setting-axes-tick-labels-format/
and the download link:
http://www.mathworks.com/matlabcentral/fileexchange/36254-ticklabelformat-set-a-dynamic-format-of-axes-tick-labels