%  This plot shows the effect of a linear transform to a normal random
%  variable.


sd_neighborhood = 5;  %  We'll plot +/- this many SDs.

%  Set up X as N(5.5, 0.5) and Y as a log transform of X. 
xMu = 5.5;
xSigma = 0.5;
yMu = log(xMu);
ySigma = xSigma/abs(xMu);
xMax = 2.2*xMu;
xValues = xMu-sd_neighborhood*xSigma:0.01:xMu+sd_neighborhood*xSigma;
xDensityValues = normpdf(xValues, xMu, xSigma);
yValues = log(xValues);
yDensityValues = normpdf(yValues, yMu, ySigma);

nValuesUsed = numel(xDensityValues);

%  The next few lines scale the x and y density values so they
%  appear nicely on the figure.  The goal is to show how the log
%  transform affects the width and location of the density, so the
%  actual scale is not important here.   
xIntegral = trapz(xDensityValues - min(xDensityValues)) / nValuesUsed;
xIntegral = trapz(yDensityValues - min(yDensityValues)) / nValuesUsed;

normalizedXDensities = (xDensityValues - min(xDensityValues)) / xIntegral;
normalizedYDensities = (yDensityValues-min(yDensityValues))/ yIntegral;

figureScaleXDensities = (log(xMu)*normalizedXDensities)/(2*max(normalizedXDensities));
figureScaleYDensities = (xMu*normalizedYDensities)/(2*max(normalizedYDensities));

%  Plot both.  
figure
orient landscape

%  Plot the x density on the horizontal axis.  
xplot = plot(xValues, figureScaleXDensities, 'k', 'LineWidth', 3);
hold on;

%  Plot the y density on the vertical axis.  
plot(figureScaleYDensities, yValues, 'k', 'LineWidth', 3)

%  Plot a line showing the relationship of the means.  
plot(1:0.01:xMax, log(1:0.01:xMax), '-k', 'LineWidth', 3)

%  Show lines for the means connecting to the diagonal line showing
%  their relationship.  
line([xMu, xMu], [0, yMu], 'LineStyle', ':', ...
     'Color', [0.8, 0.8, 0.8], 'LineWidth', 3)
line([0, xMu], [yMu, yMu], 'LineStyle', ':', ...
     'Color', [0.8, 0.8, 0.8], 'LineWidth', 3)
line([0, xMax], [yMu-sign(xMu), xMax/abs(xMu)+yMu-sign(xMu)], ...
     'Color', 'k', 'LineWidth', 3)

%  Set axis style.  
set(gca, 'Box', 'off', 'FontSize', 20, ...
         'XColor', 'w', 'YColor', 'w', ...
         'XLim', [-0.4, xMax], 'Ylim', [-0.03, log(xMax)], ...
         'XTick', [], 'YTick', [])

set(gcf, 'Position', [600, 65, 1300, 920])
pause(1)

%  Add LaTeX intrepreted labels. Locations are hard-coded here,
%  which is not generally good practice.  
meanEquation = '$y-\mu_y=\frac{1}{|\mu_x|}(x-\mu_x)  \mathbf{\rightarrow}$'
text(4.6, 2.4, equation, 'FontSize', 22, 'Interpreter', 'LaTex')
variableEquation = '$\mathbf{\leftarrow} y = log(x)$'
text(9, 2.15, variableEquation , 'FontSize', 22, 'Interpreter', 'LaTex')

xlabel('$\it\mu_x$', 'FontSize', 22, 'Color', 'k', ...
       'Interpreter', 'LaTex', ...
       'Position', [xMu, -0.07])
ylabel('$\it\mu_y$', 'FontSize', 22, 'Color', 'k', ...
       'Rotation', 0, 'Interpreter', 'LaTex', ...
       'Position', [-0.25, 1.64])