MATLAB: Plotting Time on Xaxis - overlapping label - matlab

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.

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

MATLAB: misaligned boxes in plotyy after saving as fig

I use plotyy to put two plots in one graph:
f = figure('Color','white');
[ax,p1,p2] = plotyy(xx, yy1, xx, yy2);
ylabel(ax(1),'Phase','FontSize',18);
ylabel(ax(2),'Spectrum','FontSize',18);
set(ax,{'ycolor'},{'k';'k'});
set(p1,'LineWidth',2,'Color',[0.4940,0.1840,0.5560]);
set(p2,'LineWidth',2,'Color','red');
xlabel(ax(1),['Frequency [THz]'],'FontSize',18);
set(ax,'FontSize',14)
Figure is displayed perfectly, but when I try to save it as fig something like misaligned boxes appears.
I tried to use linkaxes, but with no result.
plotyy has been one of my favorite MATLAB functions to love to hate. It's a really useful function that I always seem to run into bugs with, to the point where I've completely stopped using it in favor of just stacking two (or more) axes objects and plotting to them separately. You can then set the Position property of the 'sub' axes to the same as your primary axes and they will stack nicely.
A functional example:
xx = linspace(-15,15,100);
yy1 = sin(xx);
yy2 = cos(xx);
f = figure('Color','white');
ax(1) = axes('Parent', f);
ax(2) = axes('Parent', f, 'Color', 'none', 'XTick', [], 'YAxisLocation', 'right');
p1 = plot(ax(1), xx, yy1);
hold(ax(2), 'on'); % Hold to preserve our axes properties set above
p2 = plot(ax(2), xx, yy2);
hold(ax(2), 'off');
ylabel(ax(1),'Phase','FontSize',18);
ylabel(ax(2),'Spectrum','FontSize',18);
set(ax,{'ycolor'},{'k';'k'});
set(p1,'LineWidth',2,'Color',[0.4940,0.1840,0.5560]);
set(p2,'LineWidth',2,'Color','red');
xlabel(ax(1),'Frequency [THz]','FontSize',18);
set(ax,'FontSize',14)
set(ax, 'ActivePositionProperty', 'position'); % Resize based on position rather than outerposition
set(ax(2), 'Position', get(ax(1), 'Position')); % Set last to account for any annotation changes
Along with stacking the axes you will also note that I have set the ActivePositionProperty to position (rather than outerposition). MATLAB resizes axes automatically when the Units property is set to Normalized, and it seems like this is the main spot where the issue is arising. On resizing, MATLAB also modifies the OuterPosition value for the second axes, causing it to resize the plot portion. The difference is small, [0 0 1 1] vs. [0 0.0371 1.0000 0.9599] in my case, but the effect is obviously very pronounced. You can use get and set to fix this, but you'll have to do it on every resize which is fairly annoying. The alternative is to resize based on the Position, which seems to alleviate the issue and is a tweak present in the R2015b implementation of plotyy. This also fixes plotyy except for cases where the window is very small, so I have left my answer with the more generic approach.

Matlab and XTickLabel

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)

Plotting ticks and custom grid lines at the same time

I am trying to make a figure in Matlab that has grid lines at some custom places, but I also want to write ticks at regular intervals. Currently I produced the following graph, with the grid lines in the right position:
plot(myData);
xlabel('Frequency');
ylabel('Maginute');
set(gca, 'XTick', listOfTheoreticalValues);
set(gca,'XGrid', 'on');
set(gca, 'XTickLabel', '');
The problem I am facing now, however, is that I can't put normal, equally spaced ticks on the x-axis, let alone with marking values, because that would immediately add extra grid lines too. Is there a way to separate the two things from each other?
As Hugh Nolan suggested, manually adding grid lines is one way to solve the problem. The following code will do the trick:
%Grid line locations
x_lines = listOfTheoreticalValues;
y_limits = [lower_y_limit; upper_y_limit]; %Insert desired y-limits here
y_grid = repmat(y_limits, 1, numel(x_lines));
x_grid = [x_lines; x_lines];
plot(x_grid, y_grid, ':', 'color', [1,1,1]/2); %First plot grid lines
hold on
plot(myData); %Then plot data to draw data on top of grid lines
xlabel('Frequency');
ylabel('Maginute');

MATLAB: adding a plot to an axis

I am using plotyy to plot two vectors on different y-axes. I wish to add a third vector to one of the two axes. Can someone please tell me why the following code is not working?
[ax h1 h2] = plotyy(1:10,10*rand(1,10),1:10,rand(1,10));
hold on; plot(ax(2),1:10,rand(1,10));
??? Error using ==> plot
Parent destroyed during line creation
I simply wish to add an additional vector to one of the axes (ax(1),ax(2)) created by plotyy.
Apply hold to the axis of interest.
[ax h1 h2] = plotyy(1:10,10*rand(1,10),1:10,rand(1,10));
hold(ax(2), 'on');
plot(ax(2),1:10,rand(1,10));
plotyy works by creating two axes, one on top of the other. You are carefully adding the new vector to the second axis. The hold property is also a per-axis property, so you just need to make sure that the hold is set on the same axis.