2

我正在尝试制作一个动画,其中几个数据集在一个histogram图中循环,并且数据提示跟随每一帧中的最高条,如下所示:

                          想要的结果

这是使用条形图实现所需结果的代码:

%% // 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来自 FEX 的提交的修改版本创建的,根据提交页面上的评论(对于 27/06/2012 版本是这样makedatatip):

需要对代码进行一些更改:
***********CHANGE 1**********
第 122 行需要: pos = [X(index(n)) Y(索引(n)) 0];
***********更改 2**********
第 135-141 行应注释掉

并且还将更改 3: 第 84 行更改为Z = [];

由于makedatatip尝试访问绘图中不存在的输入句柄的'XData'和属性,因此它拒绝工作。所以我的问题是:'YData'histogram

如何在histogram绘图中以编程方式创建和更新数据提示(使用)以及直方图本身?

4

1 回答 1

2

事实证明,解决方案非常简单,至少在只需要一个数据提示时是这样。以下是所需的步骤:

  1. 用直方图替换条形图:

    hHist = histogram(data(1,:),edges);
    
  2. “手动”创建数据提示,而不是使用makedatatip

    hDataCursorMgr = datacursormode(ancestor(hHist,'figure'));
    hDT = createDatatip(hDataCursorMgr,hHist);
    
  3. 根据需要更新位置:

    hDT.Cursor.DataIndex = maxInd;
    
  4. 要更新直方图的条形高度,无法'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

结果是:

                              想要的结果 2


一些注释\观察:

  • 数据提示只能添加到支持的数据类型,目前仅由double值组成(即,绘制除双精度之外的其他内容显然不允许您向其添加数据提示)。这适用于 MATLAB 2015a。在此处查看有关它的另一个讨论。
  • 如果 datatips 应该包含一些 LaTeX 格式的字符串,这个 Q&A描述了需要做什么。
  • 我使用的 gif 动画是使用this创建的。
  • 为了使帖子中的动画居中,我使用了“alt+0160”和“alt+255”的组合。
于 2015-07-06T09:39:30.067 回答