我正在尝试制作一个动画,其中几个数据集在histogram
图中循环,并且数据提示在每帧的最高条之后,如下所示:
这是使用bar graph:
获得所需结果的代码%% // Initialization
close all force; clear variables; clc;
%% // Generate some data:
indMax = 20; data = randi(indMax,[5,45]);
%% // Generate the 1st values to plot:
edges = 0.5:1:indMax+0.5;
counts = histcounts(data(1,:),edges);
[~,maxInd] = max(counts);
%% // Create the plot and the datatip:
figure(100); hBar = bar(1:indMax,counts);
hDT = makedatatip(hBar,maxInd); hDT = handle(hDT);
grid on; hold on; grid minor; xlim([0,indMax+1]); ylim([0,10]);
%% // Update the figure and the datatip:
for indFrame = 2:size(data,1)
counts = histcounts(data(indFrame,:),edges);
[~,maxInd] = max(counts);
hBar.YData = counts; %// Update bar heights
hDT.Cursor.DataIndex = maxInd; %// Update datatip location
%// Alternatively to the above line: hDT.Position = [newX newY newZ];
java.lang.Thread.sleep(1000);
drawnow;
end
请注意,数据提示是使用makedatatip
submission from FEX的修改版本创建的,具体取决于提交页面上的注释(对于{06}的版本makedatatip
,这是正确的):< / p>
需要对代码进行一些更改:
***********更改1 *********
线122需要是:pos = [X(index(n))Y(index(n))0];
***********更改2 *********
第135-141行应注释为OUT
还将第3行 第84行改为Z = [];
由于makedatatip
尝试访问输入句柄的'XData'
和'YData'
属性,这些属性在histogram
图中不存在,因此它拒绝工作。所以我的问题是:
如何在histogram
图(使用matlab-hg2)以及直方图本身中以编程方式创建和更新数据提示?
答案 0 :(得分:2)
事实证明,解决方案非常简单,至少只需要一个数据提示。以下是必需的步骤:
用直方图替换条形图:
hHist = histogram(data(1,:),edges);
“手动”创建数据提示,而不是使用makedatatip
:
hDataCursorMgr = datacursormode(ancestor(hHist,'figure'));
hDT = createDatatip(hDataCursorMgr,hHist);
根据需要更新职位:
hDT.Cursor.DataIndex = maxInd;
要更新直方图的条形高度,无法直接更新'Values'
属性(因为它是只读的),因此必须更新'Data'
属性(并让MATLAB)重新计算自己的高度):
hHist.Data = data(indFrame,:);
所有东西放在一起:
%% // Initialization
close all force; clear variables; clc;
%% // Generate some data:
indMax = 20; data = randi(indMax,[5,45]);
%% // Generate the 1st values to plot:
edges = 0.5:1:indMax+0.5;
counts = histcounts(data(1,:),edges);
[~,maxInd] = max(counts);
%% // Create the plot and the datatip:
figure(100); hHist = histogram(data(1,:),edges);
hDataCursorMgr = datacursormode(ancestor(hHist,'figure'));
hDT = createDatatip(hDataCursorMgr,hHist); hDT.Cursor.DataIndex = maxInd;
grid on; hold on; grid minor; xlim([0,indMax+1]); ylim([0,10]);
%% // Update the plot and the datatip:
for indFrame = 2:size(data,1)
[~,maxInd] = max(histcounts(data(indFrame,:),edges));
hHist.Data = data(indFrame,:);
hDT.Cursor.DataIndex = maxInd;
java.lang.Thread.sleep(1000);
drawnow;
end
结果是:
一些注意事项\观察: