首页 > 解决方案 > 如何将误差线设置为与 Matlab 中的绘图不同的颜色?

问题描述

在 Matlab 中使用errorbar(...)误差线的颜色绘制绘图时,与绘图相同。如何将它们设置为不同的颜色?

我试着在这里寻找一种方法:

https://www.mathworks.com/help/matlab/ref/matlab.graphics.chart.primitive.errorbar-properties.html

https://www.mathworks.com/help/matlab/ref/errorbar.html

但我找不到它。

编辑:这个问题: 与图matlab不同的errobar颜色 没有我要问的答案。大约一年半前问过这个问题,但没有给出解决方案。那里的一条评论没有给出适当的解决方案。它说要绘制两次绘图 - 一次使用误差线(当绘图和误差线处于相同颜色时),第二次只是没有误差线的绘图(将使用 hold on 绘制在第一个之上) . 应该有一种方法可以用与绘图颜色不同的颜色来绘制一次图形 - 这就是我正在寻找的。

标签: matlabplotmatlab-figure

解决方案


这是一个快速而肮脏的函数实现,它允许单独设置错误栏和数据的样式。但是,在内部,它与先前发布的问题的答案相同:它使用两个图。

function varargout = mc_errorbar(ax, x,y,e, varargin)
% MC_ERRORBAR   errorbar which allows to style errorbar and data separately
%
% Usage:
%   mc_errorbar(X,Y,E) 
%     plots errorbars and a separate line in the current axis. 
%
%   mc_errorbar(X,Y,E, property, value)
%     plots errorbars and a separate line in the current axis and styles
%     the plots according to the properties given. All properties that are
%     accepted by the errorbar function are allowed, but should be prefixed
%     with 'EB'. Note that the LineStyle property will be overriden.
%     Properties not prefixed with 'EB' will be passed to the plot
%     function, hence all properties allowed by plot are allowed here, too.
%
%   mc_errorbar(ax, ___) 
%     plots in the axes ax instead of the current axes.
%     
%   [lh] = mc_errorbar(___) 
%     returns the line handle
%
%   [lh, ebh] = mc_errorbar(___)
%     returns the line handle and the handle to the errorbar
%
% See also errorbar plot

    if ~isa(ax, 'matlab.graphics.axis.Axes')
        if nargin > 3
            varargin = [{e}, varargin(:)'];
        end

        e = y;
        y = x;
        x = ax;
        ax = gca();
    end
    oldnextplot = ax.NextPlot;
    ebargs = {};
    lineargs = {};
    for k = 1:2:numel(varargin)
        if strcmp(varargin{k}(1:2),'EB') == 1
            ebargs{end+1} = varargin{k}(3:end);
            ebargs{end+1} = varargin{k+1};
        else
            lineargs{end+1} = varargin{k};
            lineargs{end+1} = varargin{k+1};
        end
    end
    ebargs{end+1} = 'LineStyle';
    ebargs{end+1} = 'none';
    eb = errorbar(ax, x, y, e, ebargs{:});
    ax.NextPlot = 'add';
    line = plot(ax, x,y, lineargs{:});
    ax.NextPlot = oldnextplot;
    if nargout > 0
        varargout{1} = line;
    end
    if nargout > 1
        varargout{2} = eb;
    end

end

例子:

mc_errorbar(1:10, (1:10)*2, (1:10)*.5, 'Color','g', 'EBColor', 'k', 'EBLineWidth', 3, 'LineStyle','-', 'LineWidth',8)

在此处输入图像描述


推荐阅读