I want to draw several histograms. But I want the Y axis to be fixed, like from 1000 to 1 by 100. How can I specify them。
Please advise.
Consider this example:
%# some data
X = randn(1000,3);
nbins = 10;
%# compute frequencies and bins
%#[count,bins] = hist(X, nbins);
count = zeros(10,size(X,2));
bins = zeros(10,size(X,2));
for i=1:size(X,2)
[count(:,i),bins(:,i)] = hist(X(:,i),nbins);
end
%# show histograms
for i=1:size(X,2)
subplot(1,size(X,2),i)
bar(bins(:,i), count(:,i),'hist')
set(gca, 'YTick',0:100:4000, 'YLim',[0 400])
end
The axis command is what you're looking for. You specify the [XMIN XMAX YMIN YMAX]. This example will have all histograms capped at a value of 5. Also, you're asking a bunch of questions about MATLAB today without seemingly doing any research. Please ask a search engine and show that you've at least tried something.
clf;
subplot(1,2,1); hist(rand(1,10)); axis([0 1 0 5]);
subplot(1,2,2); hist(rand(1,10)); axis([0 1 0 5]);
Related
I want to change the y axis of the histogram to show percentages ranging from 0 to 1. this is what I've tried, but it doesn't seem to be working.
myTolerance=1e-12; % in erg units.
nbins=50;
for j=1:ntM/100:ntM
H = histfit(Wkinet(abs(Wkinet(:,j))>myTolerance, j) * erg2eV, nbins);
%Select from column j all rows in column j whose absolute values are
%greater than the tolerance.
H(1).delete; %%Remove bins, only keep the fit.
set(gca, 'YScale', 'log');
set(gca, 'XScale', 'log'); % Make logarithmic X
yt = get(gca, 'YTick');
set(gca, 'YTick', yt, 'YTickLabel',
yt/numel(Wkinet(abs(Wkinet(:,j))>myTolerance)))
pause;
end
This is what is currently looks like:
This is what I want:
Just to simplify the discussion below, the line
H = histfit(Wkinet(abs(Wkinet(:,j))>myTolerance, j) * erg2eV, nbins);
is equivalent to
data = Wkinet(abs(Wkinet(:,j))>myTolerance, j) * erg2eV;
H = histfit(data, nbins);
This means below we'll assume data is a vector.
histfit computes and plots a histogram though histogram, then fits a function to it through fitdist. Since you don't want to plot the histogram itself, just stick to fitdist:
pd = fitdist(data,'Normal'); % this is the default distribution used in `histfit`, is it correct?
x = linspace(min(data),max(data),200); % 200 points in the graph, you might want to change this?
y = pdf(pd,x);
plot(x,y);
Now it's simple to normalize the plot however we want. For example set the first element to 1:
pd = fitdist(data,'Normal');
x = linspace(min(data),max(data),200);
y = pdf(pd,x);
y = y/y(1); % <<< Normalize
plot(x,y);
You can set limits on your y-axis using
ylim([1e-3 1]) %lower limit is nonzero since it's plotted on log scale
or
set(gca, 'ylim', [1e-3 1])
I am trying to create a figure showing the solution I obtained through Jacobi iteration along with the true solution, as well as the error of the Jacobi solution.
The figure I'm trying to create should consist of two plots.
I used the subplot command, to split the figure into
an upper and lower axes and I wrote the for loop that calculates the Jacobi iterations and the error. The loop is going to iterate 400 times using x0 as the initial guess. Before this, I calculated the true solution to the system Ax = b.
N = 30;
iter = 400;
A = toeplitz([-2 1 zeros(1, N-2)], [-2 1 zeros(1, N-2)]);
bk = ones(N,1);
for jj = 1:N
bk(jj) = cos(5*jj) + (1/2)*sin(7*jj);
end
x = A\bk;
D = diag(diag(A));
T = A - D;
x0 = zeros(N,1);
error = zeros(iter,1);
M = -D\T;
g = D\bk;
for nn = 1:iter
x0 = M*x0 + g;
error(nn) = norm(x - x0,2);
end
subplot(2,1,1)
plot(x0(1:N,1),'ro');
ylabel('Solution','FontSize',22);
title('Solution by Jacobi Iteration','FontSize',22);
xlim([0 pi]);
ylim([-5 5]);
xticks(0:0.5:3);
yticks(-5:5:5);
subplot(2,1,2)
plot(error(1:N),'ro')
ylabel('Error','FontSize',22);
xlabel('t','FontSize',22);
xlim([0 pi]);
ylim([0 0.1]);
xticks(0:0.5:3);
yticks(0:0.05:0.1);
The upper window should show the true solution in red circles connected by solid lines. The lower window show show the error as red
circles connected by dotted lines. When I ran my code, only 3 red circles appeared in the upper window and nothing was plotted in the lower window. I'm still bad at plotting iterations of a loop. Can someone help me with plotting the solutions and errors I calculated?
The xlim and ylim statements are not representative of the data.
x0 and x have N elements (30 here), and the elements of x and x0 span -2 to 2 in this setup.
error has iter elements (400 here), and the elements of error go from 4 to about 0.01.
For these plots, the element index maps to the horizontal x-axis, and their values to the y-axis. I think this plot setup should give you the result you desire (I probably changed more than actually needed):
subplot(2,1,1);
plot(1:N, x0(1:N,1), 'ro', 1:N, x,'k+');
title('Solution by Jacobi Iteration','FontSize',22);
ylabel('Solution','FontSize',22);
xlim([1, N]);
ylim([-3, 3]);
xticks(1:N);
yticks(-3:0.5:3);
subplot(2,1,2)
semilogy(1:iter, error(1:iter),'ro')
ylabel('Error','FontSize',22);
xlabel('t','FontSize',22);
xlim([1 iter]);
ylim([0 4]);
xticks(0:25:400);
I would like to plot constellation diagram similar to the figure below.
.
My approach is something like this
clc;
clear all;
close all;
N=30000;
M=16;
Sr=randint(N,1,[0,(M-1)]);
S=qammod(Sr,16,0,'gray'); S=S(:);
Noisy_Data=awgn(S,20,'measured'); % Add AWGN
figure(2)
subplot(1,2,1)
plot(S,'o','markersize',10);
grid on
subplot(1,2,2)
plot(Noisy_Data,'.');
grid on
May you assist me to make necessary modification to get graph similar to the figure attached above. Thank you.
The first thing to do would be to compute a 2D histogram of your data. This can be done with the following:
% Size of the histogram matrix
Nx = 160;
Ny = 160;
% Choose the bounds of the histogram to match min/max of data samples.
% (you could alternatively use fixed bound, e.g. +/- 4)
ValMaxX = max(real(Noisy_Data));
ValMinX = min(real(Noisy_Data));
ValMaxY = max(imag(Noisy_Data));
ValMinY = min(imag(Noisy_Data));
dX = (ValMaxX-ValMinX)/(Nx-1);
dY = (ValMaxY-ValMinY)/(Ny-1);
% Figure out which bin each data sample fall into
IdxX = 1+floor((real(Noisy_Data)-ValMinX)/dX);
IdxY = 1+floor((imag(Noisy_Data)-ValMinY)/dY);
H = zeros(Ny,Nx);
for i=1:N
if (IdxX(i) >= 1 && IdxX(i) <= Nx && IdxY(i) >= 1 && IdxY(i) <= Ny)
% Increment histogram count
H(IdxY(i),IdxX(i)) = H(IdxY(i),IdxX(i)) + 1;
end
end
Note that you can play around with parameters Nx and Ny to adjust the desired resolution of the plot. Keep in mind that the larger the histogram, the more data samples (controlled by the parameter N of your simulation) you'll need to have enough data in the histogram bins to avoid getting a spotty plot.
You can then plot the histogram as a color map based on this answer. In doing so, you likely would want to add a constant to all non-zero bins of the histogram so that the white band is reserved for zero valued bins. This would provide a better correlation with the scatter plot. This can be done with:
% Colormap that approximate the sample figures you've posted
map = [1 1 1;0 0 1;0 1 1;1 1 0;1 0 0];
% Boost histogram values greater than zero so they don't fall in the
% white band of the colormap.
S = size(map,1);
Hmax = max(max(H));
bias = (Hmax-S)/(S-1);
idx = find(H>0);
H(idx) = H(idx) + bias;
% Plot the histogram
pcolor([0:Nx-1]*dX+ValMinX, [0:Ny-1]*dY+ValMinY, H);
shading flat;
colormap(map);
After increasing N to 1000000, this gives the following plot for the data generated according to your sample:
How can I make the vertical axes of two plots equal?
For example:
a = [1 2 3; 21 1 3; 4 2 3; 4 5 6]
After plotting plot(a(1, :)) I get the following figure:
I have done some simple operations:
[U E V] = svd(a);
figure(2);
plot(U(1,:))
And get another figure:
How do I make the y-axis limits of both plots equal? Is it with the axes equal command?
UPDATE:
I've used the following commands:
figure (1)
ylim([0 3])
plot(a(1,:))
figure (2);
ylim([0 3])
plot(U(1,:))
But get the same result...
You can use ylim to force limits on the y-axis. For example:
figure(1)
%// Some plotting...
ylim([0 3])
figure(2)
%// Some more plotting
ylim([0 3])
This ensures that the y-axis is limited to the range [0, 3] in both plots. You can do the same for the limits of the x-axis with the command xlim.
Also note that if you want to set the limits for both axes at once, instead of using xlim and ylim (two commands), you can use axis (one command).
you can use the ylim or xlim functions.
You can clone the limits of one plot to another plot in this fashion:
h1 = figure;
% do first plot...
h2 = figure;
%do second plot...
% set first figure as active
figure(h1);
%get limits properties of the axes that are drawn in Figure 1
xL = get(gca, 'XLim');
yL = get(gca, 'YLim');
%switch to second figure and set it as active
figure(h2);
%set axis limit properties of Figure 2 to be the same as in Figure 1
set(gca, 'XLim', xL);
set(gca, 'YLim', yL);
I have two vectors, c and d, whose histogram I need to plot side by side in the same figure in matlab. when i do
hist(c);
hold on;
hist(d)
the scale changes and I cant see the histogram of c vector. Where am i going wrong? Any help will be appreciated.
If you want the two to be in the same figure, you could try adjusting the X and Y limits to suit your needs (try help xlim and help ylim). However plotting them in the same figure might not always suit your needs, as a particular plot has to of course maintain a certain limit for X and Y.
If displaying them side by side in different figures would suffice however, you could consider using subplot():
>> A=[1 1 1 2 2];
>> B=[1 2 2 2 2];
>> figure(1);
>> hold on;
>> subplot(1,2,1);
>> hist(A);
>> subplot(1,2,2);
>> hist(B);
Resultant figure:
Notice how the different axis limits are maintained.
You can use axis([xmin xmax ymin ymax]) to control the x and y axis and select a range that will display both histograms. Depending on what you want your plot to look like, you may also want to try using nelements = hist(___) to get the number of elements in each bin and then plot them using bar(x,nelements) to control the location of each bar.
hist assumes you want to divide the range into 10 equal sized bins by default. If you want to use the same bins for both histograms, first find the range of your values and make a set of bin centers (e.g. binCenters = linspace(min(x), max(x), 15)'), then callhist(x, binCenters)`.
I use MATLAB histograms quite frequently and have wrote this small matlab script to plot two histograms (first one red and second blue) in one figure. The script is quite simple but the important thing is that the histograms should be comparable (i.e. equally spaced frequency bins).
function myhist(varargin)
% myhist function to plot the histograms of x1 and x2 in a single figure.
% This function uses the same xvalue range and same bins to plot the
% histograms, which makes comparison possible.
if nargin<2
x1 = cell2mat(varargin(1));
x2 = x1;
res = 100;
elseif nargin==2
x1 = cell2mat(varargin(1));
if length(cell2mat(varargin(2)))==1
res = cell2mat(varargin(2));
x2 = x1;
else
x2 = cell2mat(varargin(2));
res = 100;
end
elseif nargin>2
x1 = cell2mat(varargin(1));
x2 = cell2mat(varargin(2));
res = cell2mat(varargin(3));
end
if numel(x1)~=length(x1) || numel(x2)~=length(x2)
error('Inputs must be vectors.')
return
end
xrangel = max(min(x1),min(x2));
xrangeh = min(max(x1),max(x2));
x1_tmp = x1(x1>=xrangel & x1<=xrangeh);
x2_tmp = x2(x2>=xrangel & x2<=xrangeh);
xbins = xrangel:(xrangeh - xrangel)/res:xrangeh;
hist(x1_tmp,xbins)
hold on
h = findobj(gca,'Type','patch');
set(h,'FaceColor','r','EdgeColor','w');
hist(x2_tmp,xbins)