Matlab and XTickLabel - matlab

I've been trying to get Matlab to change the labelling on my contourf plots for about an hour now. When I go to change XTickLabel or XTick, it simply removes my x-axis altogether! The frustrating and infuriating thing is that I'm doing exactly what all the help pages and help forums are asking me to do - I honestly don't understand why this is not working.
Hence, I am here.
My plotting code (knowledge of the function shouldn't be required - the code is rather intense. It is, however, a 2D contourf plot with valid data and ranges - the axes are the issue, not the graph):
contourf(time,f,power,levels)
colormap(jet(levels))
set(gca,'XTickLabelMode','manual')
set(gca, 'XTick', 0:23);
set(gca, 'XTickLabel', {'0';'1';'23'});
xlabel('Time (UT)')
ylabel('Frequency (Hz)')
caxis([0,8])
axis([0 StopTime 0 0.1])
Any help would be greatly appreciated!

Solved:
I realized that the 'XTick' relied on current values of the array I was using to define the x-axis. I can't just assume matlab will evenly space a new array (at least, if there's a way to do that, I don't know). So, since I have 85,680 data points on my X-axis, I simply rescaled it by:
set(gca, 'XTick', 0:3570:85680)
set(gca, 'XTickLabel', num2cell(0:24))
Moral of the story: Matlab doesn't let you arbitrarily stick a new axis over an old one using these two functions.

You have a final axis([0 StopTime 0 0.1])) command which clears your plot, by creating a fresh new axis. That's why all your existing plots are gone. Try removing it:
contourf(time,f,power,levels)
colormap(jet(levels))
set(gca,'XTickLabelMode','manual')
set(gca, 'XTick', 0:23);
set(gca, 'XTickLabel', {'0';'1';'23'});
xlabel('Time (UT)')
ylabel('Frequency (Hz)')
caxis([0,8])
Now the question becomes: are your ticks sensibly placed for the data you are representing? Without knowing the data I cannot answer this for you. So the ball is in your court now. ;)

You can use cell arrays to define the ticks and tick-labels and then use them with set function call, to make it more elegant -
xtick_label_cellarr = num2cell(0:24)
xtick_cellarr = linspace(0,85680,numel(xtick_label_cellarr))
set(gca, 'XTick',xtick_cellarr)
set(gca, 'XTickLabel',xtick_label_cellarr)

Related

Define Matlab Scatter Plot scale

I have the following scatter graph:
As you can see by the figure, I've defined a graph where each size of the grid is 5. I guess the grid follows the interval of the axis itself but I haven't quite figured out how change that (for example with a size 1), any help would be greatly appreciated!
The grid spacing is determined by the tick marks on the axes. Set the properties 'XTick' and 'YTick' of the axes to control the spacing of the grid, as follows:
set(gca, 'XTick', [50:75])
set(gca, 'YTick', [52:2:75])

Matlab plot numbering error

When creating a plot in Matlab the following error is produced:
I have tried many different methods of trying to find the problem and solving it. I think I have identified that the cause is because I am using multiple xlim commands. Here is my code:
figure
plot(datee,[allfile.bytes],'k','LineWidth',1.5);
hold on;
plot(datee,EMA,'--b','LineWidth',0.75);
title(sprintf('File size of %s',[token{1},dateno{1},name]));
xlabel('Month/Day');
set(gca, 'YTickLabel', num2str(get(gca,'YTick')'/1024,'%0.0f'));
datetick('x','mm/dd');
ylabel('Bytes in Kb');
plot(xlim,[ulimit ulimit], 'r')
plot(xlim,[ASize{jj} ASize{jj}], 'g')
plot(xlim,[llimit llimit], 'r')
axis tight;
axis 'auto y';
hlegend=legend('File Size','Average/EMA','Upper/Lower limit','Current Size');
set(hlegend,'Location','Best')
I do not understand why the problem occurs as it does.. And also how to solve it! Has anyone experienced this before? Since I think the xlim command is the fault, are there any other alternatives to creating a solid straight line across the whole plot?
Okay, I am unsure as to why this works, but I changed the code order very slightly to this:
figure
plot(datee,[allfile.bytes],'k','LineWidth',1.5);
hold on;
plot(datee,EMA,'--b','LineWidth',0.75);
title(sprintf('File size of %s',[token{1},dateno{1},name]));
xlimit = get(gca,'XLim');
plot(xlim,[ulimit ulimit], 'r')
plot(xlim,[ASize{jj} ASize{jj}], 'g')
plot(xlim,[llimit llimit], 'r');
xlabel('Month/Day');
set(gca, 'YTickLabel', num2str(get(gca,'YTick')'/1024,'%0.0f'));
datetick('x','mm/dd')
ylabel('Bytes in Kb');
axis tight;
axis 'auto y';
And it no longer reproduces the above bug... I have no idea why though.
If anyone ever has any suggestions/ideas, please let me know, I am very curious. Hope this helps anyone with the same problem in the future.

Matlab plot a threshold line

I want to add a horizontal threshold line to my graph of 0.7. But I can't seem to get it to work.
Code
figure(1)
plot(Variance);
hold on;
plot([1 frames], threshold, 'red')
Variance is an array to be plotted and the frames are the number of variances that are plotted. I've tried moving the hold and plots around but it doesn't seem to work either.
I know this is an easy question, but everything I've looked at online doesn't seem to work either, with regards to adding them to the same plot().
Thanks
You should change the second plot line to
plot([1 frames], [threshold threshold], 'red');

MATLAB: Plotting Time on Xaxis - overlapping label

I am having difficulties on plotting time on the xaxis. I have some overlapping labels. See below:
This is my code:
time=datenum(0,0,0,0,0,timeinseconds);
labs=1:10:length(time);
figure(3);
plotyy(time,xvalue,time,dens);
datetick('x','HH:MM');
set(gca,'XTick',time(labs),'XTickLabel',time(labs));
legend('xval','CDF');
title('Crash on Oct.10 2008 at 15:59pm');
xlabel('Time');
First, why are the labels overlapping with the old ones? And secondly, how I can get the label to rotate 90degrees? I tried some other matlab functions to turn the labels but none seem able to tackle time format labels.
Calling plotyy you create two axis objects. Your overlap problem does probably come from the fact that you modify only one set of those axis, while leaving the other as it was originally set up.
One option is handling both of the created axis when you call plotyy by:
[AX, H1, H2] = plotyy( time, xvalue, time, dens);
Your first option here is setting up both of the axis, contained within the array of handlers AX, via changing the'XTick' propriety as:
set( AX(1), 'XTick', time(labs), 'XTickLabel', time(labs));
set( AX(2), 'XTick', time(labs), 'XTickLabel', time(labs));
But you also have the option of leaving the labels for the second axis empty, replacing the second line above:
set( AX(1), 'XTick', time(labs), 'XTickLabel', time(labs));
set( AX(2), 'XTick', time(labs), 'XTickLabel', []);
The official documentation of plotyy and Using Multiple X- and Y-Axes can be of further help for you.
If you take a look on the example there, namely, plotyy documentation:
figure
x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
[AX,H1,H2] = plotyy(x,y1,x,y2,'plot');
and as you did before, try to modify only the AX(2), which is equivalent to what you got writing gca:
set(AX(2),'XtickLabel',1:0.1:20)
you will observe that the same overlapping error takes place.
With respect to rotating the labels 90 deg, I'm afraid that's not currently supported by Matlab. However, you can probably get that done using one of the available packages on FileExchange. Either xticklabelrotate or Rotate Tick Label could be the one.

How to make 1-D plots in MATLAB?

How can I make plots in MATLAB like in below?
I won't need labels, so you can ignore them. I tried using normal 2D plot, by giving 0 to y parameter for each data points. It does help, but most of the plot remains empty/white and I don't want that.
How can I solve this problem?
Edit:
This is how I plot(playing with values of ylim does not help):
hold on
for i=1:120
if genders(v_labels(i)) == CLASS_WOMAN
plot(v_images_lda(i,:) * w_lda,0,'r*');
else
plot(v_images_lda(i,:) * w_lda,0,'b.');
end
end
title('LDA 1D Plot');
ylim([-0.2 0.2]);
hold off
One way to do this would be to adjust the 'XLim', 'YLim', and 'DataAspectRatio' properties of the axes so that it renders as essentially a single line. Here's an example:
data1 = rand(1,20)./2; %# Sample data set 1
data2 = 0.3+rand(1,20)./2; %# Sample data set 2
hAxes = axes('NextPlot','add',... %# Add subsequent plots to the axes,
'DataAspectRatio',[1 1 1],... %# match the scaling of each axis,
'XLim',[0 1],... %# set the x axis limit,
'YLim',[0 eps],... %# set the y axis limit (tiny!),
'Color','none'); %# and don't use a background color
plot(data1,0,'r*','MarkerSize',10); %# Plot data set 1
plot(data2,0,'b.','MarkerSize',10); %# Plot data set 2
And you will get the following plot:
Here's one way to reproduce your figure using dsxy2figxy and annotate. dsxy2figxy can be hard to find the first time, as it is not really in your path. It is part of the MATLAB package and is provided in the example functions. You can reach it by searching for it in the help docs and once you find it, open it and save it to a folder in your path.
h1=figure(1);clf
subplot(4,1,1);
hold on
xlim([0.2,1]);ylim([-1,1])
%arrow
[arrowX,arrowY]=dsxy2figxy([0.2,1],[0,0]);
annotation('arrow',arrowX,arrowY)
%crosses
x=[0.3,0.4,0.6,0.7,0.75];
plot(x,0,'kx','markersize',10)
%pipes
p=[0.5,0.65];
text(p,[0,0],'$$\vert$$','interpreter','latex')
%text
text([0.25,0.5,0.65],[1,-1,-1]/2,{'$$d_i$$','E[d]','$$\theta$$'},'interpreter','latex')
axis off
print('-depsc','arrowFigure')
This will produce the following figure:
This is sort of a hackish way to do it, as I've tricked MATLAB into printing just one subplot. All rasterized formats (jpeg, png, etc) will not give you the same result, as they'll all print the entire figure including where the non-declared subplots should've been. So to get this effect, it has to be an eps, and it works with it because eps uses much tighter bounding boxes... so all the meaningless whitespace is trimmed. You can then convert this to any other format you want.
Ok so the closest I have come to solving this is the following
hax = gca();
hold on
for i=1:120
if genders(v_labels(i)) == CLASS_WOMAN
plot(v_images_lda(i,:) * w_lda,0,'r*');
else
plot(v_images_lda(i,:) * w_lda,0,'b.');
end
end
set(hax, 'visible', 'off');
hax2 = axes();
set(hax2, 'color', 'none', 'ytick', [], 'ycolor', get(gcf, 'color');
pos = get(hax, 'position');
set(hax2, 'position', [pos(1), pos(2)+0.5*pos(4), pos(3), 0.5*pos(4)]);
title('LDA 1D Plot');
hold off
So in short, I hid the original axis and created a new one located at 0 of the original axis, and as I couldn't remove the y axis completely I set it's color to the background color of the figure.
You can then decide if you also want to play with the tick marks of the x-axis.
Hope this helps!
Very naive trick but a useful one.
Plot in 2d using matlab plot function. Then using edit figure properties compress it to whichever axis you need a 1D plot on !! Hope that helps :)