Equally spaced x-value for values that are not equally spaced - matlab

I'm trying to display a discrete plot with values on the x-axis that are not equally space but I want them to appear equally spaced. I would like a stem plot with the first stick not on the y-axis, and I'd also like to have an horizontal dashed line at y=1.
So far here is what I tried.
x = [10 50 150 3000];
y = [.6 .754 .853 .954];
xv = [1 2 3 4];
stem(xv,y);
set(gca,'XTickLabel',x);
Unfortunately, this is not what I expected. The value on the x-axis are not right and the sticks start on the y-axis and end on the figure edge.
How can I fix this?

EDIT: I initially forgot the horizontal dashed line. Added this.
You just need two tiny additions:
x = [10 50 150 3000];
y = [.6 .754 .853 .954];
xv = [1 2 3 4];
stem(xv, y);
xlim([min(xv)-1 max(xv)+1]); % <--
set(gca, 'xtick', xv); % <--
set(gca, 'xticklabel', x);
You (also) need to explicitly set the xtick option, so that only these ticks are drawn, and no other.
With xlim, you can manipulate the x-axis limits. (Left and right limit might be modified to your needs.)
To add the horizontal dashed line, just add the following at the end:
hold on;
plot([min(xv)-1 max(xv)+1], [1 1], 'k--');
hold off;
(Start and end points of the line might be modified to your needs.)
From Matlab R2018b on, you could also use yline.
The output then looks like this:

When you have a sequence of values that you want to plot equally spaced without any special treatment to what each value actually is, you're essentially defining a set of categories.
MATLAB is good at handling these nicely without any extra trickery to lay them out uniformly on your axes if you declare the values explicitly as categorical.
All you need, therefore, is:
x = [10 50 150 3000];
y = [.6 .754 .853 .954];
stem(categorical(x),y);
yline(1,'--');
ylim([0 1.5]) % Make some space on the y-axis so the horizontal line doesn't sit on the top edge

Related

slope of lsline changes according to xaxis

I want to fit a lsline (h=lsline) to a scatterplot in MATLAB. The data is in the xrange between [-2.5 2.5] and I display them with and xlim of [-3 3]. I want to show the lsline only in the range between [-2.9 2.9].
However, when I add h.XData=[-2.9 2.9] the slope of the line changes. Does that make sense to anyone? There is no datapoint between 2.5 and 3 and I expected to only see differences in the length of the line?
Simply change the axis limits after plotting the line:
x = -2.5:.125:2.5;
y = .5 .* x + randn(1,numel(x))*.2;
scatter(x,y);
xlim([-2.9 2.9])
lsline;
xlim([-3 3])
ylim([-1.6 2])

How to insert two X axis in a Matlab a plot

I would like create a Matlab figure with a double X axis (m/s and km/h) with the same plot.
I have found plotyy and - in Matlab reposity - plotyyy, but I am looking for:
A double X axis.
Together below the plot.
My code is very simple:
stem(M(:, 1) .* 3.6, M(:, 3));
grid on
xlabel('Speed (km/h)');
ylabel('Samples');
M(:, 1) is the speed (in m/s), and M(:, 3) is the data.
I would like only a second line, in the bottom, with the speeds in m/s.
You can do something like the following. In comparison to the solution of #Benoit_11 I do use the normal Matlab labels and refer to both axes with handles so the assignments are explicit.
The following code creates an empty x-axis b with the units m/s with a negligible height. After this, the actual plot is drawn in a second axes a located a bit above the other axes and with units km/h. To plot on a specific axes, insert the axes-handle as the first argument of stem. The conversion from m/s to km/h is directly written in the call to stem. Finally, it's needed to set the xlim-property of the both axes to the same values.
% experimental data
M(:,1) = [ 0, 1, 2, 3, 4, 5];
M(:,3) = [12, 10, 15, 12, 11, 13];
% get bounds
xmaxa = max(M(:,1))*3.6; % km/h
xmaxb = max(M(:,1)); % m/s
figure;
% axis for m/s
b=axes('Position',[.1 .1 .8 1e-12]);
set(b,'Units','normalized');
set(b,'Color','none');
% axis for km/h with stem-plot
a=axes('Position',[.1 .2 .8 .7]);
set(a,'Units','normalized');
stem(a,M(:,1).*3.6, M(:,3));
% set limits and labels
set(a,'xlim',[0 xmaxa]);
set(b,'xlim',[0 xmaxb]);
xlabel(a,'Speed (km/h)')
xlabel(b,'Speed (m/s)')
ylabel(a,'Samples');
title(a,'Double x-axis plot');
As a very simple alternative you could also create a 2nd axis (transparent) and put it below the first one so that you only see the x axis.
Example:
clear
clc
close all
x = 1:10;
x2 = x/3.6;
y = rand(size(x));
hP1 = plot(x,y);
a1Pos = get(gca,'Position');
%// Place axis 2 below the 1st.
ax2 = axes('Position',[a1Pos(1) a1Pos(2)-.05 a1Pos(3) a1Pos(4)],'Color','none','YTick',[],'YTickLabel',[]);
%// Adjust limits
xlim([min(x2(:)) max(x2(:))])
text(2.85,0 ,'m/s','FontSize',14,'Color','r')
text(2.85,.05 ,'km/h','FontSize',14,'Color','r')
Output:
Then you can manually add the x labels for each unit, in different color for example.
The best way i can think to do it is to use 2 plots, for example, you can split the plot into a large and small section by doing something like this:
subplot(100, 1, 1:99) // plot your graph as you normally would
plot(...
subplot(100, 1, 100) // Plot a really small plot to get the axis
plot(...)
b = axis()
axis([b(1:2), 0, 0]) // set the y axis to really small
This is untested, you might need to fiddle around a little but it should hopefully put you on the right track.

MATLAB: how to customize non linear X axis (for example ticks at 1,2,3,4,5,20,100,'string')

I'm using the MATLAB plot feature to compare two vectors. I would like my X axis to represent 1 through 7, and then 14, 21, and then a category at the end for points with undetermined X values..(I'm also not sure how to represent these numberless point (they have Y values, just no X values) I could assign a large number outside any of my X values (1000) to these points, do the 1-7,14,21,1000 and then change the 1000 label to my 'string for un-numbered points'. ??
Here is a way to do it based on the example by The Mathworks here.
The trick is to create 2 x axis with different ranges and make one of them transparent. You can then play around with its properties. I modified a bit their code but kept most of their comments because they explain well the steps.
For the demo I used scatter to represent the points and colored the "good" points in red and the other point (here only 1) in green. You can customize all this of course. For instance I used a value of 100 and not 1000 for the x value of the 2nd axes, but I'll let you figure out how to modify it all to change the output as you wish.
clear
clc
close all
%// Create axes 1 and get its position
hAxes1 = axes;
axes_position = get(hAxes1, 'Position');
%// Create axes 2 and place it at the same position than axes 1
hAxes2 = axes('Position', axes_position);
%// Your data go here.
x = [1 7 14 21 100];
y = rand(1, length(x));
%// Plot the two sections of data on different axes objects
hPlot1 = scatter(hAxes1, x(1:4), y(1:4),40,'r','filled');
hold on
hPlot2 = scatter(hAxes2, x(end), y(end),40,'g','filled');
%// Link the y axis limits and fontsize property of the axes objects
linkaxes([hAxes1 hAxes2], 'y');
linkprop([hAxes1 hAxes2], 'FontSize');
%// Set the x range limits and tick mark positions of the first axes object
set(hAxes1, 'XLim', [1 25], ...
'XTick', [1 7 14 21])
%// Set the x range limits and tick mark positions for the second axes object.
%// Also set the background color to 'none', which makes the background
%// transparent.Add the label for the "super points".
set(hAxes2, 'Color', 'none', ...
'YTickLabel', [], ...
'XLim', [95 100], ...
'XTick', 100,'XTickLabel',{'Super Points'})
And the output:
EDIT
If you wish to add a fit line, I suggest adding a 3rd axes at the same position than the other 2, make it transparent and remove its X- and Y-ticks.
i.e. Add something like this:
hAxes3 = axes('Position', axes_position,'Color','none','YTick',[],'XTick',[]);
And in the call to polyfit/polyval, in my example you want to get only the first 4 elements (i.e. the red ones).
Hence:
p = polyfit(x(1:4),y(1:4),1);
y_poly = polyval(p,x(1:4));
And then plot the line on hAxes3:
hPlot3 = plot(x(1:4),y_poly)
Output:

Xtick marks and Xtick labels on heatmap in Matlab

Environment: Windows 7 64 bit, Matlab 2014a
Objective:
To draw a heatmap of errors for two parameters to be optimized.
To put proper tick marks and tick values
Draw the grid lines in the correct place
Problem: Arranging the X and Y tick positions and values. When the last ("end") value of the vectors in x and y axes are the same, the code I use puts the ticks and values properly. However, when the end values are different it does not, and produces something really weird.
Below I have included the code which I have modified so that you can run it without the need of adding anything. Of course in my case the error vector are the error values, not random numbers. To see the problem of "end value" use the second b vector.
fontsize = 20
k = [2^-5, 2^-3, 2^-1, 2^0, 2^1, 2^3, 2^5, 2^7, 2^9, 2^11, 2^13, 2^15]
b = [2^-5, 2^-3, 2^-1, 2^0, 2^1, 2^3, 2^5, 2^7, 2^8, 2^9, 2^10, 2^11, 2^13, 2^15]
% b = [2^-5, 2^-3, 2^-1, 2^0, 2^1, 2^3, 2^5, 2^7, 2^8, 2^9, 2^10, 2^11, 2^13, 2^19]
errorVector = randi(20, 1, length(b)*length(k))'
figure
% Create a matrix from error vector (size of error vector is [length(k)*length(b),1])
B = reshape(errorVector, [length(b), length(k)])
B = flipud(B)
% imagesc(x,y,C)
imagesc(b, k, B)
title('Heatmap Parameters Percent Error', 'FontSize', fontsize);
% Set colorbar limits
caxis([0 15])
colorbar;
ax1 = gca;
xTickLabel = (k)'
xTick = linspace(k(1), k(end), numel(xTickLabel))';
set(ax1, 'XTick', xTick, 'XTickLabel', xTickLabel)
xlabel('k parameter', 'FontSize', fontsize)
yTickLabel = (b)'
yTick = linspace(b(1), b(end), numel(yTickLabel))';
set(ax1, 'YTick', yTick, 'YTickLabel', flipud(yTickLabel(:)))
ylabel('b parameter', 'FontSize', fontsize)
set(ax1,'FontSize', fontsize)
Here, change any of the end values of b or k vectors, and the program will output a graph where the X and Y ticks are totally wrong.
Also, I would like to draw grid lines. When I use "grid on" it draws grid lines right on the tick marks which is not correct in the case of heatmap. Because tick marks will be in the center of the columns -or rows- but the grid lines should be at the boundaries between the columns -or rows.
By the way if you know a better way to plot a heatmap in Matlab, please do tell.
Please help me solve this problem. Any help is appreciated,
Ilyas
First of all - you don't need to flipud the B matrix - by default imagesc plots the y-data inversed, but you can fix this with the following statement:
set(gca,'ydir','normal');
This also means you don't have to mess around with flipping the tick-labels. You can get the labels right by doing the following:
% replace the imagesc call with:
imagesc(B);
set(gca,'ydir','normal');
% formatting stuff
...
% replace the set commands with:
set(ax1, 'XTick', 1:length(k), 'XTickLabel', k)
set(ax1, 'YTick', 1:length(b), 'YTickLabel', b)
By default, if you don't provide x and y data to the imagesc command, it will number them linearly (1,2,3...). Basically what we've done here is make sure that it has ticks for each of the elements of b and k, and then set the labels to the values of the respective vectors.
Unfortunately, I'm not sure if there is a way to get the grid spacing right with imagesc or not. You could try using pcolor instead, which has it's own set of issues, but allows you to get grid lines (of sorts) between the elements. It also allows you to use an interpolated shading mode, which will make your plot look more like a typical heat map.
To use pcolor instead, you just have to replace imagesc:
% imagesc(B);
% set(gca,'ydir','normal');
pcolor(B);
% this uses a smoother shading method, for a more 'heatmap' like output
% shading interp
Everything else should work as intended, I believe.

Linking ticks in a MATLAB plot

Is there a method of aligning tick labels?
I have a figure that has two y axes where the values vary greatly. I would like to align the tick labels so that each value shown on one y label matches up with a value on the opposite ylabel. For example:
data1 = 1+ (12-1).*rand(365,1);
data2 = 1 + (700-1).*rand(365,1);
time = 1:365;
figure(1);
ax1 = axes('position',[0.05 0.5 0.22 0.37]);
plot(time,data1,'k','linewidth',1);
ylabel('label 1');
pos=double(get(ax1,'position'));
ax2=axes('position',pos,'color','none','YAxisLocation','right','xtick',[])
hold on;
plot(time,data2,'r','linewidth',1,'parent',ax2);
ylabel(ax2,'label 2');
Here I would like the second y axis to have the same number of ticks as the first y axis as well as the same spacing between them. How can I achieve this?
Use plotyy instead of plot, it handles this for you:
plotyy(time, data1, time, data2);
You can set the y axis limits and tick locations explicitly:
ylim(ax1,[lowerBound upperBound])
set(ax1,'ytick',[tick1 tick2 tick3 tick4])
This can let you fine tune the tick locations for a particular plot. It makes zooming and panning less functional, since the ticks are often left behind.