Main Content

本页的翻译已过时。点击此处可查看最新英文版本。

具有自定义属性显示的图类

此示例说明如何定义一个具有自定义属性显示(仅显示部分属性)的图类。以下代码说明如何重载 matlab.mixin.CustomDisplay 类的 getPropertyGroups 方法。该示例还演示从 matlab.graphics.chartcontainer.ChartContainer 基类派生的图的基本编码模式。您可以通过此示例来熟悉图开发的编码方法,或基于此示例来开发您自己的类。

要定义该类,请将以下代码复制到编辑器中,并将其以名称 SmoothPlotCustomDisplay.m 保存在可写文件夹中。

classdef SmoothPlotCustomDisplay < matlab.graphics.chartcontainer.ChartContainer
    % c = SmoothPlotCustomDisplay('XData',X,'YData',Y,Name,Value,...)
    % plots a dotted line of the coordinates in X and Y with a smoothed 
    % version of the line. You can also specify additonal name-value 
    % arguments, such as 'SmoothColor' and 'SmoothWidth'.
    properties
        XData (1,:) double = NaN
        YData (1,:) double = NaN
        SmoothColor {validatecolor} = [0.9290 0.6940 0.1250]
        SmoothWidth (1,1) double = 2
    end
    properties(Access = private,Transient,NonCopyable)
        OriginalLine (1,1) matlab.graphics.chart.primitive.Line
        SmoothLine (1,1) matlab.graphics.chart.primitive.Line
    end
    
    methods(Access = protected)
        function setup(obj)
            % Get the axes
            ax = getAxes(obj);
            
            % Create the original and smooth lines
            obj.OriginalLine = plot(ax,NaN,NaN,'LineStyle',':');
            hold(ax,'on')
            obj.SmoothLine = plot(ax,NaN,NaN,'LineStyle','-',...
                'Color',[0.9290 0.6940 0.1250],'LineWidth',2);
            hold(ax,'off')
        end
        function update(obj)
            % Update line data
            obj.OriginalLine.XData = obj.XData;
            obj.OriginalLine.YData = obj.YData;
            obj.SmoothLine.XData = obj.XData;
            obj.SmoothLine.YData = createSmoothData(obj);
            
            % Update line color and width
            obj.SmoothLine.Color = obj.SmoothColor;
            obj.SmoothLine.LineWidth = obj.SmoothWidth;
        end
        function propgrp = getPropertyGroups(obj)
            if ~isscalar(obj)
                % List for array of objects
                propgrp = getPropertyGroups@matlab.mixin.CustomDisplay(obj);
                
            else
                % List for scalar object
                propList = {'SmoothColor','XData','YData'};
                propgrp = matlab.mixin.util.PropertyGroup(propList);
            end
        end
        function sm = createSmoothData(obj)
            % Calculate smoothed data
            v = ones(1,10)*0.1;
            sm = conv(obj.YData,v,'same');
        end
    end
end

保存类文件后,可以创建图的实例。如果要在创建图时查看自定义显示,请省略分号。

x = 1:1:100;
y = 10*sin(x/15)+8*sin(10*x+0.5);
c = SmoothPlotCustomDisplay('XData',x,'YData',y)
c = 

  SmoothPlotCustomDisplay with properties:

    SmoothColor: [0.9290 0.6940 0.1250]
          XData: [1x100 double]
          YData: [1x100 double]

  Use GET to show all properties

另请参阅

相关主题