How can I plot only a specific range of a curve, while having axis with higher limits? - matlab

I need to plot a section of curve, using MATLAB. But I need my axes to be larger than the part I am showing.
For example, I have the following data:
x = 0:50
y = 0.5*x
I would like to plot this data from x=0 to x=20, with xlim([0 50]).
Just to clarify, I do not want to change the range of values of x, I just want to change what is shown on the graph.

Say you have some data
x = 0:50;
y = 0.5*x;
and you would like to plot only a part of it, say everything where x<=20. You can do as follows:
index = x <= 20;
plot(x(index), y(index))
xlim(x([1,end])) % set the x-axis limit to the range of all your `x` values
ylim([min(y),max(y)]) % set the y-axis limit to the range of all your `y` values

Do this:
x = 0:20
y = 0.5*x
plot(x,y)
xlim([0 50]) % This will set x-axis to the desired range
ylim([min(y) max(y)])

Related

Matlab plot: equal distance between ticks

I have this 3D plot that I'm making but the data are not linear. This implies that on my plot, the distance between the ticks that I want to show is not equal. How can I adapt the scale of the x and y axis so that this is the case, i.e. so that the axis gets divided into equal parts with the current ticks?
I want the same ticks and tick labels, but that they just have an equal distance in between them on the axes, in stead of small between 0.1 and 0.5 and large between 1 and 5.
The current plot looks like this:
RMSEval = xlsread('RMSEvalues.xlsx');
X = RMSEval(:,1);
Y = RMSEval(:,2);
Z = RMSEval(:,3);
figure(1);
xi = linspace(min(X),max(X),30);
yi= linspace(min(Y),max(Y),30);
[XI,YI] = meshgrid(xi,yi);
ZI = griddata(X,Y,Z,XI,YI);
contourf(XI,YI,ZI);
colormap('jet');
xticks([1e-13 5e-13 1e-12 5e-12 1e-11]);
yticks([1e-18 5e-18 1e-17 5e-17 1e-16]);
colorbar;
A plot where the distance between 0.1 and 0.5 is the same as between 1 and 5 would be a log plot, specifically a log-log plot since you want it on both axes. One way to achieve this would be to transform the X and Y values of your data logarithmically and modify the tick mark labels to match the untransformed values rather than the logarithmic ones you're actually plotting.
A rough guess at a solution is below. I say a rough guess because without posting the data you're importing from the xlsx file or a paired down version of that data (as in an MWE) I can't actually test it.
RMSEval = xlsread('RMSEvalues.xlsx');
X = log(RMSEval(:,1));
Y = log(RMSEval(:,2));
Z = RMSEval(:,3);
figure(1);
xi = linspace(min(X),max(X),30);
yi= linspace(min(Y),max(Y),30);
[XI,YI] = meshgrid(xi,yi);
ZI = griddata(X,Y,Z,XI,YI);
contourf(XI,YI,ZI);
colormap('jet');
xticks(log([1e-13 5e-13 1e-12 5e-12 1e-11]));
xticklabels(cellfun(#num2str,num2cell(),'UniformOutput',false));
yticks(log([1e-18 5e-18 1e-17 5e-17 1e-16]));
yticklabels(cellfun(#num2str,num2cell([1e-18 5e-18 1e-17 5e-17 1e-16]),'UniformOutput',false));
colorbar;

In Matlab, how to draw lines from the curve to specific xaxis position?

I have a spectral data (1000 variables on xaxis, and peak intensities as y) and a list of peaks of interest at various specific x locations (a matrix called Peak) which I obtained from a function I made. Here, I would like to draw a line from the maximum value of each peaks to the xaxis - or, eventually, place a vertical arrow above each peaks but I read it is quite troublesome, so just a vertical line is welcome. However, using the following code, I get "Error using line Value must be a vector of numeric type". Any thoughts?
X = spectra;
[Peak,intensity]=PeakDetection(X);
nrow = length(Peak);
Peak2=Peak; % to put inside the real xaxis value
plot(xaxis,X);
hold on
for i = 1 : nbrow
Peak2(:,i) = round(xaxis(:,i)); % to get the real xaxis value and round it
xline = Peak2(:,i);
line('XData',xline,'YData',X,'Color','red','LineWidth',2);
end
hold off
Simple annotation:
Here is a simple way to annotate the peaks:
plot(x,y,x_peak,y_peak+0.1,'v','MarkerFaceColor','r');
where x and y is your data, and x_peak and y_peak is the coordinates of the peaks you want to annotate. The add of 0.1 is just for a better placing of the annotation and should be calibrated for your data.
For example (with some arbitrary data):
x = 1:1000;
y = sin(0.01*x).*cos(0.05*x);
[y_peak,x_peak] = PeakDetection(y); % this is just a sketch based on your code...
plot(x,y,x_peak,y_peak+0.1,'v','MarkerFaceColor','r');
the result:
Line annotation:
This is just a little bit more complicated because we need 4 values for each line. Again, assuming x_peak and y_peak as before:
plot(x,y);
hold on
ax = gca;
ymin = ax.YLim(1);
plot([x_peak;x_peak],[ymin*ones(1,numel(y_peak));y_peak],'r')
% you could write instead:
% line([x_peak;x_peak],[ymin*ones(1,numel(y_peak));y_peak],'Color','r')
% but I prefer the PLOT function.
hold off
and the result:
Arrow annotation:
If you really want those arrows, then you need to first convert the peak location to the normalized figure units. Here how to do that:
plot(x,y);
ylim([-1.5 1.5]) % only for a better look of the arrows
peaks = [x_peak.' y_peak.'];
ax = gca;
% This prat converts the axis unites to the figure normalized unites
% AX is a handle to the figure
% PEAKS is a n-by-2 matrix, where the first column is the x values and the
% second is the y values
pos = ax.Position;
% NORMPEAKS is a matrix in the same size of PEAKS, but with all the values
% converted to normalized units
normpx = pos(3)*((peaks(:,1)-ax.XLim(1))./range(ax.XLim))+ pos(1);
normpy = pos(4)*((peaks(:,2)-ax.YLim(1))./range(ax.YLim))+ pos(2);
normpeaks = [normpx normpy];
for k = 1:size(normpeaks,1)
annotation('arrow',[normpeaks(k,1) normpeaks(k,1)],...
[normpeaks(k,2)+0.1 normpeaks(k,2)],...
'Color','red','LineWidth',2)
end
and the result:

How do you rescale the height of a histogram?

I am having trouble plotting a histogram of the x-values of my data points together with a line showing the relationship between x and y, mainly because the scale in the y direction of the histogram is not of the same magnitude as the scale in the line plot. For example:
% generate data
rng(1, 'twister')
x = randn(10000,1);
y = x.^2
% plot line, histogram, then histogram and line.
subplot(3,1,1)
scatter(x, y, 1, 'filled')
ax = gca;
maxlim = max(ax.XLim); % store maximum y-value to rescale histogram to this value
subplot(3,1,2)
h = histogram(x, 'FaceAlpha', 0.2)
subplot(3,1,3)
scatter(x, y, 1, 'filled')
hold on
h = histogram(x, 'FaceAlpha', 0.2)
Produces the following:
where the line chart is completely obscured by the histogram.
Now, one might naively try to rescale the histogram using:
h.Values = h.Values/max(h.Values) * maxlim;
which gives
You cannot set the read-only property 'Values' of Histogram.
Alternatively one can get the bin counts using histcounts, but as far as I can tell, the bar function does not allow one to set the face alpha or have other configurability as per the call to histogram.
As discussed in the comments there are several solutions that depend on the version of Matlab you are using. To restate the problem, the histogram function allows you to control many graphics properties like transparency, but only gives you a limited number of options to change the height of the bars. With histcounts you can get the bar heights and rescale them however you want, but you must plot the bars yourself.
First option: use histogram
As you cannot rescale the histogram heights, you must plot them on separate axis.
From release 2016a and onwards, you can use yyaxis left for the scatter plot and yyaxis right for the histogram, see Matlab documentation:
Prior to this one must manually create and set separate y-axis. Although I have not found a good simple example of this, this is perhaps the most relevant answer here: plot two histograms (using the same y-axis) and a line plot (using a different y-axis) on the same figure
Using histcounts and manually creating a bar chart
Using my example, we can get counts as follows:
[Values, Edges] = histcounts(x);
And rescaling:
Values = Values / max(Values) * maxlim;
and finding centres of bars:
bar_centres = 0.5*(Edges(1:end-1) + Edges(2:end));
Up to release 2014a, bar charts had a 'children' property for the patches that allows transparency to be controlled, e.g.:
% plot histogram
b1 = bar(bar_centres,Values);
% change transparency
set(get(b1,'Children'),'FaceAlpha',0.3)
After 2014a bar charts no longer have this property, and to get around it I plot the patches myself using the code from this mathworks q&a, replicated here:
function ptchs = createPatches(x,y,offset,c,FaceAlpha)
%createPatches.m
% This file will create a bar plot with the option for changing the
% FaceAlpha property. It is meant to be able to recreate the functionality
% of bar plots in versions prior to 2014b. It will create the rectangular
% patches with a base centered at the locations in x with a bar width of
% 2*offset and a height of y.
% Ensure x and y are numeric vectors
validateattributes(x,{'numeric'},{'vector'});
validateattributes(y,{'numeric'},{'vector'});
validateattributes(c,{'char'},{'scalar'});
%#TODO Allow use of vector c
% Check size(x) is same as size(y)
assert(all(size(x) == size(y)),'x and y must be same size');
% Default FaceAlpha = 1
if nargin < 5
FaceAlpha = 1;
end
if FaceAlpha > 1 || FaceAlpha <= 0
warning('FaceAlpha has been set to 1, valid range is (0,1]');
FaceAlpha = 1;
end
ptchs = cell(size(x)); % For storing the patch objects
for k = 1:length(x)
leftX = x(k) - offset; % Left Boundary of x
rightX = x(k) + offset; % Right Boundary of x
ptchs{k} = patch([leftX rightX rightX leftX],...
[0 0 y(k) y(k)],c,'FaceAlpha',FaceAlpha, ...
'EdgeColor', 'none');
end
end
I made one change: that is, imposed the no edge condition. Then, it is perfectly fine to use:
createPatches(bin_centres, Values, 1,'k', 0.2)
to create the bars.

pcolor in scatter plot matlab

I have a large matrix DAT(50000+,42). I am plotting 2 rows of this matrix on the x and y axes, and want the plot points to vary in color due to the value of a separate row. Can anybody advise? pcolor will not work for me due to "color data input must be a matrix" error.
TIA
X = DAT(:,21);
Y = DAT(:,22);
Z = DAT(:,28);
plot(X,Y,'*');
hold on
pcolor(X,Y,Z);
hold off
You could consider using scatter()
% random sample data
DAT = randn(30,42);
X = DAT(:,21);
Y = DAT(:,22);
Z = DAT(:,28);
scatter(X,Y,50,Z); % x,y,size,color -> size can also be a vector
% scatter(X,Y,50,Z,'*'); % to also change the marker type
You can select the colors from an array generated with colormap like this:
DAT = randn(30,42);
X = DAT(:,21);
Y = DAT(:,22);
Z = DAT(:,28);
[dummy ID]=sort(Z);
colors=colormap(jet(length(Z)));
figure
for i=1:length(Z)
plot(X(i),Y(i),'*','Color',colors(ID(i),:));
hold on
end
The only issue with this technique is that you cannot do plots with millions of points because of the looped plotting, but otherwise it works like a charm:

How can I create a plot like this in MATLAB?

I am trying to plot the ranges of different cellular base stations in MATLAB, like this:
But I can't figure out how to do it.
Here's an example of how you can create a plot like this. Note that I created sample data for the plot by randomly generating the positions of cellular base stations using uniformly distributed pseudorandom numbers:
%# Initializations:
minRange = 0; %# Lower x and y range
maxRange = 3.5; %# Upper x and y range
resolution = 1000; %# The number of data points on the x and y axes
cellRange = linspace(minRange, maxRange, resolution);
[x, y] = meshgrid(cellRange); %# Create grids of x and y coordinates
cellCoverage = zeros(size(x)); %# Initialize the image matrix to zero
%# Create the sample image data:
numBases = 200;
cellRadius = 0.75;
for iBase = 1:numBases
point = rand(1,2).*(maxRange - minRange) + minRange;
index = ((x - point(1)).^2 + (y - point(2)).^2) <= cellRadius^2;
cellCoverage(index) = cellCoverage(index) + 1;
end
%# Create the plot:
imagesc(cellRange, cellRange, cellCoverage); %# Scaled plot of image data
axis equal; %# Make tick marks on each axis equal
set(gca, 'XLim', [minRange maxRange], ... %# Set the x axis limit
'YLim', [minRange maxRange], ... %# Set the y axis limit
'YDir', 'normal'); %# Flip the y axis direction
xlabel('X-distance (km)'); %# Add an x axis label
ylabel('Y-distance (km)'); %# Add a y axis label
colormap(jet); %# Set the colormap
colorbar; %# Display the color bar
And here's the resulting plot:
Note also that the data in the image matrix cellCoverage contains no noise and has no smoothing applied, which is why the edges appear sharper than the original image in the post (which I'm guessing is generated from real data, not "fake" sample data like I used here).
Use "image"
image(x),colormap(hsv) <- where x is a matrix of cellular intensities(x,y)
You need to get the coordinate of each station then create a circle polygon around it (with a given radius), then convert this polygon into a grid. Then you sum up these grids (matrices) on top of each other. For speed, instead of using polygons you can also define which cells will be covered by a station, like all cells within 5 rows or columns of a station get the value.
You can also apply a 2D Gaussian filter to your matrix, where only the cells containing a station have a value of 1. The bandwidth of your Gaussian kernel will be your coverage radius (range). http://www.mathworks.ch/help/toolbox/images/ref/fspecial.html