Hist3 Plotting and Axes Range - matlab

I'm plotting a 3-D histogram with MATLAB and it's working pretty ok, except for the different axes ranges. I'd like them to be defined in a way, where equal value pairs lie on the bisecting line.
My code looks like this (more or less "stolen" from the hist3 MATLAB example):
[vec_voxel_ids, vec_dose_values_reference, vec_dose_values_control] = ...
textread('_BOOSTINT_voxel_data.txt', '%u %u %u');
mat_dose_values = [vec_dose_values_reference, vec_dose_values_control];
hist3(mat_dose_values, [100, 100]);
xlabel('Dose Reference');
ylabel('Dose Control');
set(gcf, 'renderer', 'opengl');
set(get(gca,'child'), 'FaceColor', 'interp', 'CDataMode', 'auto');
This is how it looks:

In order to reposition the bins to align their centers the ticks and also choose the range of the bin values you can use hist3's 'edges' option (similar to that in histc):
data = 500+5*randn(1e3,2); % dummy data
d = 1; % width for x and y bins
x = 480:d:520; % range for x bins
y = x; % use same range for y bins, can be different
hist3(data, 'edges', {x-d/2,y-d/2}); % subtract half bin width to center bins
set(gcf, 'renderer', 'opengl');
set(get(gca,'child'), 'FaceColor', 'interp', 'CDataMode', 'auto');
view(2)
axis equal
axis([478 522 478 522])
grid minor
xlabel('x')
ylabel('y')
This example produces something like this:
Note, that this is a re-binning of your data so your output may look slightly different compared to before. The bins have been shifted to align their centers and the histogram recalculated.

Related

Remove Exponents from Matlab LOG-LOG plot

I am trying to plot several frequency response curves on a logx and logy plot. I also want the axes to show values without exponents.
I cannot figure out a way to plot the log scale AND remove exponents. Using the following, I can only either set my scale to log, OR remove exponents. Not both.
figure(3);clf;
hold on;
%set(gca,'YScale', 'log', 'XScale', 'log')); %This doesnt work with ax.XAxis.Exponent = 0;
plot(freq, Pxx,'r', 'LineWidth', 1.5, 'DisplayName', 'Single-Sided Spectral Density');
ax=gca;
ax.XAxis.Exponent = 0; %remove exponents
ax.YScale = 'log'; %Log Y
ax.XScale = 'log'; %Log X
xlabel('Frequency [Hz]');ylabel('[WU^2 / Hz]');
title('Average Single-Sided Spectral Density [G_x_x] vs. Frequency')
grid on;
xlim([0 max(freq)]);legend('FontSize',14);
hold off
Plot with log scale, AND Exponents in scale values
Plot without log scale, without exponents in scale values
Changing the tick labels can be done like this:
figure;loglog([12 123 1233],[12 144 1111]);
set(gca,'xticklabel',arrayfun(#(x) num2str(x),(get(gca,'xtick')),'un',0))
set(gca,'yticklabel',arrayfun(#(x) num2str(x),(get(gca,'ytick')),'un',0))

How to turn y axis of histogram to show percentage ranging from 0 to 1

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])

How to format graph so that border starts at max x and y and how to replace a plot command

I am trying to format my graph so that the border ends at the max x and max y so there is not extra space between them and the border. Also, I'm trying to completely replace my first plot command with my second one. Should I just delete my first plot? Currently, the second plot goes over my first plot, removing most of my formatting.
clear all, close all
%%command to clear all variables and log history
x = linspace(-pi, pi, 200);
%creating x variable between - pi and 200 with pi distance between each
%value
y = sin(x) + cos(x);
%Creating y varable with the help of x
figure
plot(x,y)
title('2-D Plot')
xlabel('Theta (in radians)')
ylabel('Function Y')
xlim([-pi pi])
ylim([-1.414 1.414])
grid
plot(x,y,'r--')
grid
To fit the axes box tightly around the data without manually adjusting the axis limits, use:
axis tight;
and instead of re-plotting, you can update the relevant properties of the line.
x = linspace(-pi, pi, 200);
y = sin(x) + cos(x);
figure;
h = plot(x,y); %handle for the line plot
title('2-D Plot');
xlabel('Theta (in radians)');
ylabel('Function Y');
grid;
axis tight; %to set the axis limits equal to the range of the data
set(h, 'LineStyle', '--', 'Color', 'r'); %Updating the plot with required changes

How to plot a histogram as a scatter plot in matlab?

The y axis should be frequency (which is the histogram part) while the x axis is the xdata used to plot the histogram. Essentially what I need is exactly a histogram but instead of bars, there should be points.
I'd do that using the histcounts command. It's like the histogram command, but instead of plotting the data, it returns the number in each bin and the bin edges. You can then plot that as points using the general plot command.
x = randn(1,1000); %Generate some data to plot
figure(1); clf;
subplot(2,1,1); hold on;
h = histogram(x,'normalization','probability');
title('Plotted as a histogram');
ylabel('Frequency');
subplot(2,1,2); hold on;
[N, edges] = histcounts(x,'normalization','probability');
centers = (edges(1:end-1) + edges(2:end))./2; %histcounts gives the bin edges, but we want to plot the bin centers
plot(centers,N,'ko');
title('Plotted as points');
ylabel('Frequency');

Adding space between cells in Matlab imagesc output

I am creating a 2D plot in Matlab by calling this command: imagesc(vector1, vector2, mat_weights). Then, I run the colorbar command.
I now have a smooth 2D plot, but I want to add space between the cells. Here's how I want it to look:
How do I add such spacing between the cells/boxes?
You can add spaces between patches of color using another function than imagesc. Here, scatter provides a straightforward solution when used with option 'filled' and marker 'square'.
Note that you need to transform your 2-D matrix into a vector, but you don't have to scale your data: scatter takes the min and max values from your data and assign them to the min and max colors of the colormap.
The code
% 2-D in 1-D:
Z = diag(1:10); %example of 2-D matrix to be plotted
C = reshape(Z,1,[]); %1-D transform for vector color
% input definition
sz_matrix = 10;
X = repmat( (1:sz_matrix), 1, sz_matrix);
Y = kron(1:sz_matrix,ones(1,sz_matrix));
S = 1000; % size of marker (handle spaces between patches)
%C = (X.^2 + Y.^2); % second color scheme
%plot
figure('Color', 'w', 'position', [10 10 600 400]);
scatter(X, Y, S, C, 'fill', 's');
set(gca, 'XLim', [0 11], 'YLim', [0 11]);
axis square;
colormap summer
colorbar
will give
EDIT
Here is a piece of code for a rectangular matrix. Please note the inversion of the Y axis direction so that the graphical representation matches disp(Z). To have similar (x,y) proportion in the white area separating color patches, one may try to resize manually the figure.
Z = diag(1:10); %example of 2-D matrix to be plotted
Z = Z(1:end-2,:); %trim for rectangular
% input definition
X = repmat(1:size(Z,2), 1, size(Z,1));
Y = kron(1:size(Z,1),ones(1,size(Z,2)));
C = reshape(Z',1,[]); %1-D transform for vector color
S = 1000; % size of marker (handle spaces between patches)
%plot
figure('Color', 'w');
scatter(X, Y, S, C, 'fill', 's');
set(gca, 'XLim', [0 size(Z,2)+1], 'YLim', [0 size(Z,1)+1]);
colormap jet
colorbar
set(gca, 'YDir','reverse');
The ouput: