MATLAB画柱状图填充(多种)

本文介绍了一个Matlab函数applyhatch的应用,该函数能够将指定的图案应用于图表中不同的颜色区域,实现黑白图案填充效果。文章提供了两个示例,分别是柱状图和饼状图的图案填充,并附带了详细的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、把下列代码保存为名为“applyhatch.m”的文件

function applyhatch(h,patterns,colorlist)
%APPLYHATCH Apply hatched patterns to a figure
%  APPLYHATCH(H,PATTERNS) creates a new figure from the figure H by
%  replacing distinct colors in H with the black and white
%  patterns in PATTERNS. The format for PATTERNS can be
%    a string of the characters '/', '\', '|', '-', '+', 'x', '.'
%    a cell array of matrices of zeros (white) and ones (black)
%
%  APPLYHATCH(H,PATTERNS,COLORS) maps the colors in the n by 3
%  matrix COLORS to PATTERNS. Each row of COLORS specifies an RGB
%  color value.
%
%  Note this function makes a bitmap image of H and so is limited
%  to low-resolution, bitmap output.
%
%  Example 1:
%    bar(rand(3,4));
%    applyhatch(gcf,'\-x.');
%
%  Example 2:
%    colormap(cool(6));
%    pie(rand(6,1));
%    legend('Jan','Feb','Mar','Apr','May','Jun');
%    applyhatch(gcf,'|-+.\/',cool(6));
%
%  See also: MAKEHATCH


%  By Ben Hinkle, bhinkle@mathworks.com
%  This code is in the public domain. 
  
oldppmode = get(h,'paperpositionmode');
oldunits = get(h,'units');
set(h,'paperpositionmode','auto');
set(h,'units','pixels');
figsize = get(h,'position');
if nargin == 2
  colorlist = [];
end
bits = hardcopy(h,'-dzbuffer','-r0');
set(h,'paperpositionmode',oldppmode);


bwidth = size(bits,2);
bheight = size(bits,1);
bsize = bwidth * bheight;
if ~isempty(colorlist)
  colorlist = uint8(255*colorlist);
  [colors,colori] = nextnonbw(0,colorlist,bits);
else
  colors = (bits(:,:,1) ~= bits(:,:,2)) | ...
           (bits(:,:,1) ~= bits(:,:,3));
end
pati = 1;
colorind = find(colors);
while ~isempty(colorind)
  colorval(1) = bits(colorind(1));
  colorval(2) = bits(colorind(1)+bsize);
  colorval(3) = bits(colorind(1)+2*bsize);
if iscell(patterns)
    pattern = patterns{pati};
  elseif isa(patterns,'char')
    pattern = makehatch(patterns(pati));
  else
    pattern = patterns;
  end
  pattern = uint8(255*(1-pattern));
  pheight = size(pattern,2);
  pwidth = size(pattern,1);
  ratioh = ceil(bheight/pheight);
  ratiow = ceil(bwidth/pwidth);
  bigpattern = repmat(pattern,[ratioh ratiow]);
  if ratioh*pheight > bheight
    bigpattern(bheight+1:end,:) = [];
  end
  if ratiow*pwidth > bwidth
    bigpattern(:,bwidth+1:end) = [];
 end
  bigpattern = repmat(bigpattern,[1 1 3]);
  color = (bits(:,:,1) == colorval(1)) & ...
          (bits(:,:,2) == colorval(2)) & ...
          (bits(:,:,3) == colorval(3));
  color = repmat(color,[1 1 3]);
  bits(color) = bigpattern(color);
  if ~isempty(colorlist)
    [colors,colori] = nextnonbw(colori,colorlist,bits);
  else
    colors = (bits(:,:,1) ~= bits(:,:,2)) | ...
             (bits(:,:,1) ~= bits(:,:,3));
  end
  colorind = find(colors);
  pati = (pati + 1);
  if pati > length(patterns)
    pati = 1;
  end
end


newfig = figure('units','pixels','visible','off');
imaxes = axes('parent',newfig,'units','pixels');
im = image(bits,'parent',imaxes);
fpos = get(newfig,'position');
set(newfig,'position',[fpos(1:2) figsize(3) figsize(4)+1]);
set(imaxes,'position',[0 0 figsize(3) figsize(4)+1],'visible','off');
set(newfig,'visible','on');


function [colors,out] = nextnonbw(ind,colorlist,bits)
out = ind+1;
colors = [];
while out <= size(colorlist,1)
  if isequal(colorlist(out,:),[255 255 255]) | ...
        isequal(colorlist(out,:),[0 0 0])
    out = out+1;
  else
    colors = (colorlist(out,1) == bits(:,:,1)) & ...
             (colorlist(out,2) == bits(:,:,2)) & ...
             (colorlist(out,3) == bits(:,:,3));
    return
  end
end


% 而applyhatch函数需要调用下面的函数
function A = makehatch(hatch)
%MAKEHATCH Predefined hatch patterns
%  MAKEHATCH(HATCH) returns a matrix with the hatch pattern for HATCH
%   according to the following table:
%      HATCH        pattern
%     -------      ---------
%        /          right-slanted lines
%        \          left-slanted lines
%        |          vertical lines
%        -          horizontal lines
%        +          crossing vertical and horizontal lines
%        x          criss-crossing lines
%        .          single dots
%
%  See also: APPLYHATCH


%  By Ben Hinkle, bhinkle@mathworks.com
%  This code is in the public domain.


n = 6;
A=zeros(n);
switch (hatch)
case '/'
  A = fliplr(eye(n));
case '\'
  A = eye(n);
case '|'
  A(:,1) = 1;
case '-'
  A(1,:) = 1;
case '+'
  A(:,1) = 1;
  A(1,:) = 1;
case 'x'
  A = eye(n) | fliplr(diag(ones(n-1,1),-1));
case '.'
  A(1:2,1:2)=1;
otherwise
  error(['Undefined hatch pattern "' hatch '".']);
end


2、画柱状填充图

代码:
data = [96.3,92.6,71.2;95.7,93.6,83.9;96.8,94.3,78.3;95.8,92.7,80.3];
bar(data,1);
axis([0 6 0.0 100]);
legend('方法','exited','Square');
set(gca,'XTickLabel',{'Img1','Img2','Img3','Img4'});
set(gcf,'color','white')
 applyhatch(gcf,'\.x.');


3、画饼状填充图

代码:
x = [0.14, 0.24, 0.05, 0.47, 0.1];
pie(x);
set(gcf,'color','white')
applyhatch(gcf,'|-+.\');

### 带填充效果的柱状图绘制方法 在 MATLAB 中,可以通过自定义函数或工具箱来实现带有纹理填充柱状图。以下是基于已有资源[^1]、[^2]、[^3] 和 [^4] 提供的一种解决方案。 #### 示例代码:绘制带纹理填充的多柱状图 以下是一个完整的示例代码,用于创建具有不同纹理填充的多柱状图: ```matlab % 数据准备 data = [5, 10; 15, 20; 25, 30]; % 示例数据矩阵 (n组 * m列) groupNames = {'Group A', 'Group B', 'Group C'}; % 组名 barWidth = 0.8; % 条形宽度 % 创建条形图对象 figure; hBar = bar(data, barWidth, 'stacked'); % 使用堆叠模式以便后续处理 hold on; % 设置颜色透明度(便于观察纹理) for i = 1:length(hBar) set(hBar(i), 'FaceAlpha', 0.5); end % 添加纹理填充 patterns = {'\','/','-','|','.','o','*','#','$','%','@'}; numPatterns = length(patterns); for i = 1:length(hBar) xData = get(hBar(i), 'XData'); yData = get(hBar(i), 'YData'); % 获取当前图案 currentPattern = patterns(mod(i-1, numPatterns)+1); % 绘制纹理填充 arrayfun(@(j) text(xData(j), yData(j)/2, repmat(currentPattern, 1, round(yData(j))), ... 'FontSize', 10, 'Color', 'k'), 1:size(yData, 2)); end % 添加数据标签 for i = 1:length(hBar) for j = 1:numel(hBar(i).XData) value = hBar(i).YData(j); % 当前值 text(hBar(i).XData(j), hBar(i).YData(j) + max(data(:))*0.05, ... sprintf('%.1f', value), 'VerticalAlignment', 'bottom', 'HorizontalAlignment', 'center'); end end % 图表美化 set(gca, 'XTickLabel', groupNames); xlabel('Groups'); ylabel('Values'); title('Multi-Bar Chart with Texture Filling and Data Labels'); legend({'Column 1', 'Column 2'}, 'Location', 'northwest'); grid on; hold off; ``` --- ### 关键点解析 1. **数据结构设计** 输入的数据 `data` 是一个多维数组,每一列表示一组柱状图的高度。通过调整该变量可以轻松扩展到更多分组或多列的情况。 2. **纹理填充逻辑** 利用了 `text()` 函数,在每个矩形内部重复绘制特定字符作为纹理。这些字符存储在一个字符串数组中,循环调用以匹配每根柱子的颜色或位置。 3. **透明度设置** 调整 `FaceAlpha` 属性使背景部分半透明,从而让叠加的纹理更加清晰可见。 4. **动态标注数值** 对于每一个柱体顶部都附加了一个精确显示其高度的小型文字标记,增强了可读性和科学表达力[^4]。 --- ###
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值