正如評論中所討論的,有幾種解決方案取決於您使用的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)
創建吧。
您可以更改條形圖的臉部alpha(https://www.mathworks.com/matlabcentral/newsreader/view_thread/243589),因此使用'histc'可能是更智能的方法。 – Dan
感謝,'直方圖'配置的其他屬性也可以用類似的神祕方式訪問嗎? – Alex
很可能。另一種選擇是在第二y軸上繪製折線圖或直方圖 – Dan