matlab - 如何在 Matlab 图形中添加工具提示或叠加文本

标签 matlab tooltip overlay matlab-figure mouseover

我有一个有两条或更多条线的图形。这些线有额外的、与之相关的重要信息,比如平均有多少数据点来创建线等。我想在我的图中访问这些信息。

我认为一个很好的解决方案是,如果您可以将鼠标悬停在一条线上并获得扩展信息。

然而,在图形上搜索工具提示/覆盖/悬停似乎没有结果。

例子:

figure; hold on;
plot(1:10,rand(10,1))
plot(1:10,rand(10,1))
% additional info
plot_1_info.name = 'Alice';
plot_2_info.name = 'Bob';
plot_1_info.age = 24;
plot_2_info.age = 12;

对此有什么好的解决方案或更好的方法吗?

最佳答案

您可以更改数据游标行为,此选项具有良好的向后兼容性(我在 R2017b 中测试了以下内容,之前在 15b 中使用类似)。

data cursor

详情见我的评论:

% Create some data
x = (1:2:20).';
y = rand(10,1);
name = { 'Alice'; 'Alice'; 'Alice'; 'Alice'; 'Bob'; 'Bob'; 'Bob'; 'Chris'; 'Chris'; 'Chris' };
age = [ 24; 24; 24; 24; 12; 12; 12; 17; 17; 17 ];
% Put it in a table, so we have it all together for indexing as plot data
tbl = table( x, y, name, age );

% Create the plot, assign the UserData property to the plot object
f = figure; 
plt = plot( x, y );
plt.UserData = tbl;

% Hijack the Data Cursor update callback so we can inject our own info
dcm = datacursormode( f );
set( dcm, 'UpdateFcn', @onDataCursor );

% Function which returns the text to be displayed on the data cursor
function txt = onDataCursor( ~, evt )
    % Get containing figure
    f = ancestor( evt.Target, 'figure' );
    % Get the index within the original data
    idx = getfield( getCursorInfo( datacursormode( f ) ), 'DataIndex' );
    % The original data is stored in the UserData property
    data = evt.Target.UserData;
    % Each element of the cell array is a new line on the cursor
    txt = { sprintf( 'X: %g', data.x(idx) ), ...
            sprintf( 'Y: %g', data.y(idx) ), ...
            sprintf( 'Name: %s', data.name{idx} ), ...
            sprintf( 'Age: %g', data.age(idx) ) };          
end

输出:

plot with data tip

注意:我没有在任何地方处理有多个数据游标提示的情况。您可以轻松地在回调中通过 idx 实现循环来处理这个问题,我把它留作练习。


这种方法非常灵活。例如,如果我们有 3 行(每个“人”一行),那么他们每个人都可以有自己的 UserData 结构,我们不需要重复表行中的所有信息。

A = struct( 'X', 1:4, 'Y', rand(1,4), 'Name', 'Alice', 'Age', 24 );
B = struct( 'X', 1:3, 'Y', rand(1,3), 'Name', 'Bob', 'Age', 12 );
C = struct( 'X', 1:3, 'Y', rand(1,3), 'Name', 'Chris', 'Age', 17 );

f = figure; hold on;
plt = plot( A.X, A.Y ); plt.UserData = A;
plt = plot( B.X, B.Y ); plt.UserData = B;
plt = plot( C.X, C.Y ); plt.UserData = C;

% ... Now the struct fields can be accessed from the callback

关于matlab - 如何在 Matlab 图形中添加工具提示或叠加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55355813/

相关文章:

java - 相当于 Matlab 的 "randsample"随机样本

jquery - 页面加载后,鼠标悬停功能首次不起作用

javascript - 谷歌地理图表 map : tooltip without region name

flash - 下拉菜单出现在 Flash 视频后面

html - 用jquery在html中覆盖按钮img

matlab - 是否可以避免在元胞数组上迭代时出现 "s{1} annoyance"?

matlab - 在不同状态序列长度的 MATLAB 中估计马尔可夫链转移矩阵

matlab - 尝试从 Matlab 中的 COM 端口读取数据时出现“没有可用端口”错误

c# - 将 DataGridCell 工具提示属性绑定(bind)到 DataGridCell 的值

android - 在 Android 上查看时,网站覆盖内容不会滚动