【问题标题】:How can I change the color of a specific bin in a histogram?如何更改直方图中特定 bin 的颜色?
【发布时间】:2010-12-17 18:45:21
【问题描述】:

我在 MATLAB 中编写了一个绘制直方图的代码。我需要将其中一个垃圾箱着色为与其他垃圾箱不同的颜色(比如说红色)。有人知道怎么做吗?例如,给定:

A = randn(1,100);
hist(A);

如何使 0.7 属于红色的 bin?

【问题讨论】:

    标签: matlab plot histogram


    【解决方案1】:

    制作两个重叠条形图(如Jonas suggests)的另一种方法是调用bar 将分箱绘制为一组patch objects,然后修改'FaceVertexCData' property 以重新着色补丁面:

    A = randn(1,100);                 %# The sample data
    [N,binCenters] = hist(A);         %# Bin the data
    hBar = bar(binCenters,N,'hist');  %# Plot the histogram
    index = abs(binCenters-0.7) < diff(binCenters(1:2))/2;  %# Find the index of the
                                                            %#   bin containing 0.7
    colors = [index(:) ...               %# Create a matrix of RGB colors to make
              zeros(numel(index),1) ...  %#   the indexed bin red and the other bins
              0.5.*(~index(:))];         %#   dark blue
    set(hBar,'FaceVertexCData',colors);  %# Re-color the bins
    

    这是输出:

    【讨论】:

    • 在看到直方图只是一个对象后,我什至没有检查条形系列是否为您提供了单独的句柄。 +1 表示更加小心。
    【解决方案2】:

    我想最简单的方法是先绘制直方图,然后在其上绘制红色 bin。

    A = randn(1,100);
    [n,xout] = hist(A); %# create location, height of bars
    figure,bar(xout,n,1); %# draw histogram
    
    dx = xout(2)-xout(1); %# find bin width
    idx = abs(xout-0.7) < dx/2; %# find the bin containing 0.7
    hold on;bar([xout(idx)-dx,xout(idx),xout(idx)+dx],[0,n(idx),0],1,'r'); %# plot red bar
    

    【讨论】:

    • @ariel: 看来我打电话给bar 时弄错了。现在它应该可以工作了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2018-12-30
    • 2020-12-16
    • 2018-02-17
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多