【问题标题】:Plotting histogram side by side in Matlab在 Matlab 中并排绘制直方图
【发布时间】:2013-03-25 13:41:08
【问题描述】:

我有两个向量 c 和 d,我需要在 matlab 的同一个图中并排绘制它们的直方图。当我做 历史(c); 坚持,稍等; 历史(d) 比例发生变化,我看不到 c 向量的直方图。我哪里错了?任何帮助将不胜感激。

【问题讨论】:

    标签: matlab histogram


    【解决方案1】:

    如果您希望两者在同一个数字中,您可以尝试调整 XY 限制以满足您的需求(尝试 help xlimhelp ylim)。然而,将它们绘制在同一个图中可能并不总是适合您的需求,因为特定的绘图当然必须为 XY 保持一定的限制。

    如果将它们并排显示在不同的图中就足够了,您可以考虑使用subplot()

    >> A=[1 1 1 2 2];
    >> B=[1 2 2 2 2];
    >> figure(1);
    >> hold on;
    >> subplot(1,2,1);
    >> hist(A);
    >> subplot(1,2,2);
    >> hist(B);
    

    结果图:

    注意不同的轴限制是如何保持的。

    【讨论】:

      【解决方案2】:

      您可以使用axis([xmin xmax ymin ymax]) 来控制 x 轴和 y 轴并选择将显示两个直方图的范围。根据您希望绘图的样子,您可能还想尝试使用 nelements = hist(___) 获取每个 bin 中的元素数量,然后使用 bar(x,nelements) 绘制它们以控制每个条的位置。

      【讨论】:

        【解决方案3】:

        hist 假设您希望默认将范围划分为 10 个大小相等的 bin。如果您想对两个直方图使用相同的 bin,首先找到值的范围并制作一组 bin 中心(例如 binCenters = linspace(min(x), max(x), 15)'), then callhist(x, binCenters)`。

        【讨论】:

          【解决方案4】:

          我经常使用 MATLAB 直方图,并编写了这个小的 matlab 脚本来在一个图中绘制两个直方图(第一个是红色的,第二个是蓝色的)。该脚本非常简单,但重要的是直方图应该具有可比性(即等间距的频率箱)。

          function myhist(varargin)
          % myhist function to plot the histograms of x1 and x2 in a single figure. 
          % This function uses the same xvalue range and same bins to plot the
          % histograms, which makes comparison possible. 
          if nargin<2
              x1 = cell2mat(varargin(1));
              x2 = x1;
              res = 100;
          elseif nargin==2
              x1 = cell2mat(varargin(1));
              if length(cell2mat(varargin(2)))==1
                  res = cell2mat(varargin(2));
                  x2 = x1;
              else
                  x2 = cell2mat(varargin(2));
                  res = 100;
              end
          elseif nargin>2
              x1 = cell2mat(varargin(1));
              x2 = cell2mat(varargin(2));
              res = cell2mat(varargin(3));
          end
          
          if numel(x1)~=length(x1) || numel(x2)~=length(x2)
              error('Inputs must be vectors.')
              return
          end
          
          xrangel = max(min(x1),min(x2));
          xrangeh = min(max(x1),max(x2));
          
          x1_tmp = x1(x1>=xrangel & x1<=xrangeh);
          x2_tmp = x2(x2>=xrangel & x2<=xrangeh);
          
          xbins = xrangel:(xrangeh - xrangel)/res:xrangeh;
          
          hist(x1_tmp,xbins)
          hold on 
          h = findobj(gca,'Type','patch');
          set(h,'FaceColor','r','EdgeColor','w');
          hist(x2_tmp,xbins)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-03-18
            • 1970-01-01
            • 2011-09-22
            • 2017-12-17
            • 2019-07-20
            • 2011-12-08
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多