How do I place the Date and Time on my horizontal axis to be in separate rows in a figure in MATLAB? - matlab

I am plotting a graph of random data versus datetime strings. These datetime strings are all in one line and serve as labels on the horizontal axis. I would like the date to be displayed in one line and the time to be in another line.
The image below describes my graph. I would like the time to be displayed underneath the date.
The code I used to generate the graph is shown below:
figure
plot(sample(:,1),sample(:,2:5),'o')
tick=get(gca,'xtick');
set(gca,'xticklabel',datestr(tick,31))
drawnow()
How can I get the time of each horizontal label to appear below the date?

This is a bit of a hack, but you can introduce the TeX command \newline inside the date string in between the spaces of the date and the time, then set these new strings to be the X Tick labels in your figure. You'll need to convert the character array that is output from datestr into a cell array of strings with cellstr, then use strrep to perform the replacement from a space to \newline.
Something like this should work:
figure
plot(sample(:,1),sample(:,2:5),'o')
tick=get(gca,'xtick');
vals = cellstr(datestr(tick,31)); %// Change
new_vals = strrep(vals, ' ', '\newline'); %// New
set(gca,'xticklabel',new_vals); %// Change
drawnow()
When I do this with a sample plot:
plot(1:6, 1:6, 'r.');
I get this as the final result once I run the code:
Take note that this assumes that the X Ticks are sufficiently spaced apart from each other. Your plot will look cluttered if you have many ticks on the horizontal axis.

Related

Matlab 2016a - how to get xTickLabels on only some of the xTicks on an imagesc?

I'm trying to create a 24x366 heatmap using imagesc with the x-axis labelled at 13 evenly spaced points as {'jan 15','feb 15',...,'dec 15','jan 16'}, and the y-axis labelled at every row from 1 to 24, like this:
Desired imagesc axes
When I run the script, it displays the y-axis as I want it, but it only displays the first label on the x axis and ignores the others. I can get this to work for a plot, but I can't get it to work for an imagesc. I've included my script below. Does anyone know how to make the imagesc display all 13 labels on the x-axis at evenly spaced intervals?
mylabels = {'jan 15','feb 15','mar 15','apr 15','may 15','jun 15','jul 15','aug 15','sep 15','oct 15','nov 15','dec 15','jan 16'};
testspacing = (1:(60*24*30):528480);
figure
imagesc(rand(24,366))
set(gca,'XTick',testspacing,'XTickLabel',mylabels,'XTickLabelRotation',45,'YTick',1:24,'YTickLabel',1:24)
The problem with your code is that your only one of your ticks from testspacing falls in the range of the plot testspacing=[1 43201 ...]. You can check the range of your x-axis by running xlim without any arguments.
You can rescale testspacing to fit your x-axis e.g. like:
xmax = 366;
mylabels = {'jan 15','feb 15','mar 15','apr 15','may 15','jun 15','jul 15','aug 15','sep 15','oct 15','nov 15','dec 15','jan 16'};
testspacing = (1:(60*24*30):528480);
testspacing = testspacing/max(testspacing)*xmax;
figure
imagesc(rand(24,xmax))
set(gca,'XTick',testspacing,'XTickLabel',mylabels,'XTickLabelRotation',45,'YTick',1:24,'YTickLabel',1:24)
or you just generate testspacing properly. Since you are putting own labels on the axis anyway you might just choose use testspacing = [0:30.5:366] or testspacing = [0:30:366] depending on what you want. This will also help you debug your own code later on.
On another note you should think about reducing the number of labels in general and decide which of the labels are really helpful. Maybe every 2nd or 3rd month is enough. You can "remove" individual labels by setting them to empty strings ''.

Plotting hidden variable/parameter

I would like to plot some parametric plots as a function of a 0-1 variable.
I can easily set up x=linspace(0,1) and define functions a(x), b(x), and plot(a,b).
What I would like to do, however, is indicated in the plotted diagrams the value of my original x parameter. I would guess there is a function to do so, although I haven't found it yet. Optionally, I could also do a color gradient with a bar along each trace for my 0-1. Can anyone point me in the right direction?
Good news! You can do all sort of things quite easily, let's start with defining some data:
x = linspace(0,1);
a = sin(5.*x);
b = cos(6.*x);
Now, we make a simple plot:
plot(x,a,'-o',x,b,'^')
The '-o' means the first series of data (a) will be plotted as line with circle markers, the '^' means the second series of data (b) will be plotted with no line, just triangles. You can find all options here.
Next, we call:
text(x(50)+0.03,a(50),sprintf('x = %0.3f',x(50)),'FontSize',14)
text(x(30)+0.03,b(30),sprintf('x = %0.3f',x(30)),'FontSize',14)
the text command print text at specific coordinates on the figure. For example, the first line will print in (x(30)+0.03,a(30)) the text "x = 0.495". The text string is formatted with another function sprintf, but you can just write simple text in single quote marks (').
Finally, we can add legend by:
legend({'sin(5x)','cos(6x)'},'FontSize',16,'Location','SouthWest')
note that the text strings are in a cell array.
And we get the result:
That's the kind of stuff you have been looking for?

Matlab: Format the decimals in contour labels

I want to cut the number of decimals in the following contour plot. I do:
[cc,hh] = contour(X,Y,Z,levels,'LineColor','k');hold on
texth = clabel(cc,hh,'FontSize',8);
which gets me the first contour with long labels. Then in order to cut the decimals I do:
for i = 1:size(texth); textstr=get(texth(i),'String'); textnum=str2double(textstr); textstrnew=sprintf('%0.0f', textnum) ; set(texth(i),'String',textstrnew); end
And this gives the second plot. As you see, there is a wide gap between the label and the contour lines which looks awful. Any ideas how to solve this?
Instead of modifying the result, create a contour plot with the levels you want, so you don't need to cheat the data.
Define levels as e.g. levels=997:1010
and then
contour(X,Y,Z,levels,'LineColor','k','ShowText','on');
Will create a contour plot with the text included and the levels being specifically the ones in the variable levels, in this case 997,998,999,...,1009,1010
If, as #David suggests, your levels variable already is a vector, then replace it by round(levels) as himself suggested.

Ignoring non-specified points in matlab plot

how can we ignore the non-specified values in x-axis label of a matlab plot?
for ex:
if my
x=[201:210];,y=rand(size(x));
I would like to display only those specified values of x such as 201,202,203..instead of with the intermediate values such as 201.5,202.5.. Basically I wanna get rid of these decimal values in my plot.
thanks in advance.
DURAI
If you don't want to plot them. You can just specify your variables used in plot.
plot(x(1:2:end),y(1:2:end))
this would plot only each second value. Obviously you can use logical indexing and any other means e.g. another index-array as well.
plot(x(x>10),y(x>10))
as another example. Just take care that you use the same commands in both variables otherwise you will get wrong results or an error (if number of points don't match up).
If you want to plot specific values you can use a for loop to loop over the values you want to use:
x=1:1:10;
y=115:15:250;
figure(2)
for x=[4,5,7]
display(x)
plot(x,y(x),'x'); hold on
end
If you want to just change the area which is displayed but use the whole set of data points you can use:
axis([xmin,xmax,ymin,ymax])
or if you want to change the labels of x-axis use:
set(gca, 'XTick',new_x_axis_steps, 'XTickLabel',new_x_labels(new_x_axis_steps))
where new_x_axis_steps is an array which defines the start, end point and the step and new_x_labels is what you want to write there (if you want to use strings), otherwise just use:
set(gca, 'XTick',new_x_axis_steps)

In Matlab: How to keep all xTicks but xTicklabels just on every 6 xTicks?

I have created a graph with data from an Excel file. I need to keep all the xticks but the xticklabels to appear just on every 6 ticks. I have tried doing this:
tickStep=6;
Sheet=2;
filename='MyData.xlsx';
[~,xAxis]=xlsread(filename,Sheet,'A2:A60');
yAxis=xlsread(filename,Sheet,'B2:B60');
plot(1:numel(xAxis),yAxis)
set(gca,'xtick',1:numel(xAxis))
set(gca,'xticklabel',xAxis(1:tickStep:numel(xAxis)))
Unfortunately it does not work as all the xticks are plotted, but the xticklabels appear upon each xtick instead of every 6th like I was trying to achieve. I have spent quite a long time thinking about the solution:-(. I need help. Thanks.
edit: I've included an image to help answer questions below:
In relation to this post, would it also be possible that the xticks appear every 4 xticks instead of keeping all of them, at the same time that the xticklabels are plotted every 6 xticks?, not sure about this.
You still need to enter an empty string (or empty cell) for the ticks that will have no label. You can do this by replacing the last line with these three lines:
xTickLabels = cell(1,numel(xAxis)); % Empty cell array the same length as xAxis
xTickLabels(1:tickStep:numel(xAxis)) = xAxis(1:tickStep:numel(xAxis));
% Fills in only the values you want
set(gca,'XTickLabel',xTickLabels); % Update the tick labels
Edit in response to questions below...
The reason your labels appear to be offset from the ticks is because the bottom of the letters appears to be getting lined up with the tick mark. I'm guessing you want the text justified such that the center of each letter lines up with the tick mark. There's no way to do this with the standard MATLAB axes, but there are some submissions on the MathWorks File Exchange that convert the tick labels to text objects and thus give you more options for customizing the text properties:
XTICKLABEL_ROTATE by Brian Katz
Format Tick Labels by Alexander Hayes
Once you convert the labels to text objects, you can then adjust the rotation or vertical justification by modifying the 'Rotation' and 'VerticalAlignment' properties, respectively.