色彩映射发生变化时执行功能

Tim*_*Tim 5 matlab plot callback matlab-guide

我正在开发一个GUI控件MATLAB(2014a)程序,其中有一个绘图窗口,contour在一个pcolor基于图的绘图上显示一个类似的图.

用户发现,colormap可以通过右键单击颜色条来更改.然而,这种变化只会pcolor直接影响绘图,因为我的contour函数内部.

我已经找到了如何colormap从我的轴对象中获取更改并将其应用于contour绘图,但我仍然需要手动重做绘图.

有没有一次执行任何回调colormapaxes/ figure对象改变?

我读到了PropertyChangeCallback,但colormap似乎并没有存储为属性.

Hok*_*oki 1

您无需借助未记录的功能来拦截colormapHG2 之前的 Matlab 中的更改。您只需将侦听器附加到'PostSet'属性的事件即可'Colormap'

举个简单的例子,如果你的图形已经存在,只需输入:

lh = addlistener( h.fig , 'Colormap' , 'PostSet' , @(h,e) disp('cmap changed !') )
Run Code Online (Sandbox Code Playgroud)

在控制台中,每次更改colormap. 请注意,以下情况都会触发该事件:

  • 您将其colormap完全更改为另一个(例如,从jet到)hsv
  • 您更改颜色图的大小(划分数)。(前任:colormap(jet(5))
  • 您使用“交互式色彩图转换”GUI 工具。

请注意,如果您使用 ,该事件将不会caxis触发。此命令不会更改其colormap本身,而是更改某些颜色映射到它的方式。因此,如果您使用此命令,您的命令pcolor将会被修改(尽管颜色图不会)。该caxis命令更改CLim当前的属性axes(不是figure!)。因此,如果您想检测到这一点,则必须将侦听器附加到正确轴上的此属性。就像是:

lh = addlistener( gca , 'CLim' , 'PostSet' , @(h,e) disp('clim changed !') )
Run Code Online (Sandbox Code Playgroud)

作为一个更实用的示例,这里有一个小演示,每次colormap更改时都会做出反应。由于我不知道您计划contour在每次更改时对绘图执行什么操作,因此我只是修改了几个属性以表明它正在执行某些操作。将其调整为您需要执行的操作。

function h = cmap_change_event_demo

%// SAMPLE DATA. create a sample "pcolor" and "contour" plot on a figure
nContour = 10 ;
[X,Y,Z] = peaks(32);
h.fig = figure ;
h.pcol = pcolor(X,Y,Z) ;
hold on;
[~,h.ct] = contour(X,Y,Z,nContour,'k');
h.cb = colorbar
shading interp
colormap( jet(nContour+1) ) %// assign a colormap with only 10+1 colors

%// add the listener to the "Colormap" property
h.lh = addlistener( h.fig , 'Colormap' , 'PostSet' , @cmap_changed_callback )

%// save the handle structure
guidata( h.fig , h )

function cmap_changed_callback(~,evt)
    %//  disp('cmap changed !')

    hf   = evt.AffectedObject ; %// this is the handle of the figure
    cmap = evt.NewValue ;       %// this is the new colormap. Same result than : cmap = get(hf,'Colormap') ;

    h = guidata( hf ) ;         %// to retrieve your contour handles (and all the other handles)
    nColor = size(cmap,1) ;     %// to know how many colors are in there if you want matching contours

    %// or just do something useless
    set(h.ct , 'LineColor' , rand(1,3) )      %// change line color
    set(h.ct , 'LineWidth' , randi([1 5],1) ) %// change line thickness
Run Code Online (Sandbox Code Playgroud)

cmap_event_demo