你如何重新调整直方图的高度?

时间:2016-05-12 06:21:49

标签: matlab

我无法绘制x - 我的数据点值的直方图以及显示xy之间关系的线,主要是因为{ {1}}直方图的方向与线图中的比例的大小不同。例如:

y

产生以下内容:

enter image description here

直方图完全遮盖折线图。

现在,人们可能会天真地尝试使用以下方法重新缩放直方图:

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

给出了

h.Values = h.Values/max(h.Values) * maxlim;

或者可以使用You cannot set the read-only property 'Values' of Histogram. 获取bin计数,但据我所知,histcounts函数不允许设置face alpha或具有其他可配置性。 bar

1 个答案:

答案 0 :(得分:0)

正如评论中所讨论的,有几种解决方案取决于您正在使用的Matlab版本。要重述此问题,histogram功能允许您控制许多图形属性,如透明度,但只提供有限数量的选项来更改条形的高度。使用histcounts,您可以获得条形高度并根据需要重新缩放它们,但您必须自己绘制条形图。

第一个选项:使用histogram

由于无法重新缩放直方图高度,因此必须在不同的轴上绘制它们。

从版本2016a开始,您可以使用yyaxis left作为散点图,使用yyaxis right作为直方图,请参阅Matlab documentation

在此之前,必须手动创建并设置单独的y - 轴。虽然我没有找到一个很好的简单例子,但这可能是最相关的答案:plot two histograms (using the same y-axis) and a line plot (using a different y-axis) on the same figure

使用histcounts并手动创建条形图

使用我的例子,我们可以得到如下计数:

[Values, Edges] = histcounts(x);

重新调整:

Values = Values / max(Values) * maxlim;

找到酒吧中心:

bar_centres = 0.5*(Edges(1:end-1) + Edges(2:end));

最新发布2014a,条形图具有允许控制透明度的补丁的“子”属性,例如:

% plot histogram
b1 = bar(bar_centres,Values);
% change transparency
set(get(b1,'Children'),'FaceAlpha',0.3)

2014a条形图之后不再具有此属性,为了解决这个问题,我使用此mathworks q&a中的代码自行绘制补丁,并在此处复制:

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

我做了一个改变:就是强加无边缘条件。然后,完全没问题:

createPatches(bin_centres, Values, 1,'k', 0.2)

创建栏。

相关问题