How can I assign multiple colors to tick labels in plots in MATLAB?

后端 未结 3 1052
耶瑟儿~
耶瑟儿~ 2020-12-19 13:33

Is it possible to color a single number (or a set of numbers) on one of the axes in MATLAB?

Suppose I have a plot:

plot(1:10, rand(1,10))


        
相关标签:
3条回答
  • 2020-12-19 13:36

    As an alternative to copying the entire axes contents, it is possible to do this also by creating additional axes objects:

    ax = axes();
    p = plot(1:10, rand(1,10));
    myTick = 3;
    
    % Create new axes with transparent backgrounds
    ax2 = axes();
    ax3 = axes();
    set([ax2 ax3], 'XLim', xlim(ax));
    set([ax2 ax3], 'Color', 'none');
    
    set(ax3, 'XTick', [], 'YTick', []);
    
    % Give one new axes a single tick mark
    set(ax2, 'YTick', []);
    set(ax2, 'XTick', myTick);
    set(ax2, 'XColor', 'r');
    
     % This line is necessary to use the plot toolbar functions like zoom / pan
    linkaxes([ax ax2 ax3]);
    
    0 讨论(0)
  • 2020-12-19 13:39

    Single tick labels can be colored using tex markup, which is enabled for tick labels by default. It is defined in the TickLabelInterpreter property of the axis.

    It provides two commands for coloring text:

    • \color{<name>}, where <name> is a color name like “red” or “green“, and
    • \color[rgb]{<R>,<G>,<B>}, where <R>, <G> and <B> are numbers between 0 and 1 and define an RGB color.

    These commands can be used to color single tick labels:

    plot(1:10, rand(1,10))
    ax = gca;
    
    % Simply color an XTickLabel
    ax.XTickLabel{3} = ['\color{red}' ax.XTickLabel{3}];
    
    % Use TeX symbols
    ax.XTickLabel{4} = '\color{blue} \uparrow';
    
    % Use multiple colors in one XTickLabel
    ax.XTickLabel{5} = '\color[rgb]{0,1,0}green\color{orange}?';
    
    % Color YTickLabels with colormap
    nColors = numel(ax.YTickLabel);
    cm = jet(nColors);
    for i = 1:nColors
        ax.YTickLabel{i} = sprintf('\\color[rgb]{%f,%f,%f}%s', ...
            cm(i,:), ax.YTickLabel{i});
    end
    

    And this is how the result looks:

    The code worked for me in MATLAB R2016b and R2017a.

    0 讨论(0)
  • 2020-12-19 13:46

    Unfortunately, you cannot have multiple colors for tick labels in one axes object. However, there's a solution (inspired by this page from MathWorks support site) that achieves the same effect. It overlays the existing axes it with another axes that has only one red tick.

    Here's an example:

    figure
    plot(1:10, rand(1,10))
    ax2 = copyobj(gca, gcf);                             %// Create a copy the axes
    set(ax2, 'XTick', 3, 'XColor', 'r', 'Color', 'none') %// Keep only one red tick
    ax3 = copyobj(gca, gcf);                             %// Create another copy
    set(ax3, 'XTick', [], 'Color', 'none')               %// Keep only the gridline
    

    The result is:

    result

    0 讨论(0)
提交回复
热议问题