【MATLAB基础绘图第2棒】绘制柱状/饼图填充图


带填充纹理的堆叠图是通过在原始堆叠图的基础上添加不同的纹理得到的,可以很好地解决由于 颜色区分不够而导致的对象识别困难问题。

由于Matlab中未收录提供填充纹理选项,因此需要大家自行设法解决。本博客介绍三种填充方法。

方法1:hatchfill2工具

MATLAB官网-Hatchfill2(Kesh Ikuma. Matlab Central, 2023)
在这里插入图片描述

1.1 案例1:柱状图填充

成图如下:
在这里插入图片描述
MATLAB代码如下:

clc
close all
clear
%% 基本设置
pathFigure= '.\Figures\' ;

%% Example 1:柱状图填充

figure(1);
h = bar(rand(3,4));
xlabel('Xlabel','fontsize',14,'FontName','Times New Roman','FontWeight','Bold')
ylabel('Ylabel','fontsize',14,'FontName','Times New Roman','FontWeight','Bold')
set(gca,'Layer','top','FontSize',14,'Fontname', 'Times New Roman');

str= strcat(pathFigure, "Figure1", '.tiff');
print(gcf, '-dtiff', '-r600', str);

figure(2);
hp = bar(rand(3,4));
xlabel('Xlabel','fontsize',14,'FontName','Times New Roman','FontWeight','Bold')
ylabel('Ylabel','fontsize',14,'FontName','Times New Roman','FontWeight','Bold')
set(gca,'Layer','top','FontSize',14,'Fontname', 'Times New Roman');
hatchfill2(hp(1),'single','HatchAngle',0);
hatchfill2(hp(2),'cross','HatchAngle',45);
hatchfill2(hp(3),'single','HatchAngle',90);

str= strcat(pathFigure, "Figure2", '.tiff');
print(gcf, '-dtiff', '-r600', str);

此外,也可以尝试黑白配色(FaceColor设置为白色即可):

1.2 案例2:饼图填充

成图如下:
在这里插入图片描述
MATLAB代码如下:

clc
close all
clear
%% 基本设置
pathFigure= '.\Figures\' ;

%% Example 2:饼图填充

figure(3);
colormap(cool(4));
h = pie(rand(4,1));
th = findobj(gca, 'Type', 'text');
set(th, 'FontName', 'Times New Roman', 'FontSize', 12)
hl = legend('Jan','Feb','Mar','Apr','May','Jun');
set(hl,'Box','off','Location','southOutside','NumColumns',3);
set(gca,'Layer','top','FontSize',14,'Fontname', 'Times New Roman');

str= strcat(pathFigure, "Figure3", '.tiff');
print(gcf, '-dtiff', '-r600', str);

figure(4);
colormap(cool(4));
hp = pie(rand(4,1));
hatchfill2(hp(1,1),'single','HatchAngle',0);
hatchfill2(hp(1,3),'cross','HatchAngle',45);
hatchfill2(hp(1,5),'single','HatchAngle',60);
hatchfill2(hp(1,7),'single','HatchAngle',90);
th = findobj(gca, 'Type', 'text');
set(th, 'FontName', 'Times New Roman', 'FontSize', 12)
hl = legend(hp(1, [1,3,5,7]),'Jan','Feb','Mar','Apr');
set(hl,'Box','off','Location','southOutside','NumColumns',3);
set(gca,'Layer','top','FontSize',14,'Fontname', 'Times New Roman');

str= strcat(pathFigure, "Figure4", '.tiff');
print(gcf, '-dtiff', '-r600', str);

方法2:applyhatch函数

Documentation of applyhatch

调用函数如下:

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

%  Copyright 2002-2009 The MathWorks, Inc.
  
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
if verLessThan('matlab','8.4.0')
  bits = hardcopy(h,'-dzbuffer','-r0');
else
  bits = print(h,'-RGBImage','-r0');
end
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');
end

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

end


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

%  Copyright 2002-2009 The MathWorks, Inc.

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

end

2.1 案例1:柱状图填充

成图如下:
在这里插入图片描述
MATLAB代码如下:

clc
close all
clear
%% 基本设置
pathFigure= '.\Figures\' ;


%% Example 1:

figure(1);
h = bar(rand(3,4));
xlabel('Xlabel','fontsize',14,'FontName','Times New Roman','FontWeight','Bold')
ylabel('Ylabel','fontsize',14,'FontName','Times New Roman','FontWeight','Bold')
set(gca,'Layer','top','FontSize',14,'Fontname', 'Times New Roman');
str= strcat(pathFigure, "Figure1", '.tiff');
print(gcf, '-dtiff', '-r600', str);

applyhatch(gcf,'\-x.');
set(gca,'Layer','top','FontSize',14,'Fontname', 'Times New Roman');

str= strcat(pathFigure, "Figure2", '.tiff');
print(gcf, '-dtiff', '-r600', str);

2.2 案例2:饼图填充

成图如下:
在这里插入图片描述
MATLAB代码如下:

clc
close all
clear
%% 基本设置
pathFigure= '.\Figures\' ;

%% Example 2:

figure(3);
colormap(cool(4));
h = pie(rand(4,1));
th = findobj(gca, 'Type', 'text');
set(th, 'FontName', 'Times New Roman', 'FontSize', 12)
hl = legend('Jan','Feb','Mar','Apr','May','Jun');
set(hl,'Box','off','Location','southOutside','NumColumns',3);
set(gca,'Layer','top','FontSize',14,'Fontname', 'Times New Roman');

str= strcat(pathFigure, "Figure3", '.tiff');
print(gcf, '-dtiff', '-r600', str);

applyhatch(gcf,'|-+.', cool(4));
set(gca,'Layer','top','FontSize',14,'Fontname', 'Times New Roman');


str= strcat(pathFigure, "Figure4", '.tiff');
print(gcf, '-dtiff', '-r600', str);

方法3: applyhatch_plusC函数

MATLAB官网-applyhatch_plusC函数
在这里插入图片描述
但是问题来了,在较新版本(如R2019a)的matlab中将applyhatch函数中用到的hardcopy函数去掉了,会提示 “未定义函数或变量 ‘hardcopy’”错误。

一个简单的解决方案是将以下代码进行替换

bits = hardcopy(h,'-dzbuffer',['-r' num2str(dpi)]);
bits = print('-RGBImage');

但是最后的结果很差,图像失真很严重,并且不能调整。因此并不建议用此函数。

3.1 案例1:柱状图填充

成图如下:
在这里插入图片描述
MATLAB代码如下:

clc
close all
clear
%% 基本设置
pathFigure= '.\Figures\' ;

% 图片尺寸设置(单位:厘米)
% ----------------------------------------------
figureUnits = 'centimeters';
figureWidth = 35;
figureHeight = 30;


%% Example 1:柱状图填充

figureHandle = figure;
set(gcf, 'Units', figureUnits, 'Position', [0 0 figureWidth figureHeight]); % define the new figure dimensions
h = bar(rand(3,4));
xlabel('Xlabel','fontsize',14,'FontName','Times New Roman','FontWeight','Bold')
ylabel('Ylabel','fontsize',14,'FontName','Times New Roman','FontWeight','Bold')
set(gca,'Layer','top','FontSize',14,'Fontname', 'Times New Roman');

str= strcat(pathFigure, "Figure1", '.tiff');
print(gcf, '-dtiff', '-r600', str);


[im_hatch1,colorlist] = applyhatch_pluscolor(gcf,'\-x.',0,0,[],150);

str= strcat(pathFigure, "Figure2", '.tiff');
print(gcf, '-dtiff', '-r600', str);

3.2 案例2:饼图填充

成图如下:
在这里插入图片描述
MATLAB代码如下:

clc
close all
clear
%% 基本设置
pathFigure= '.\Figures\' ;

% 图片尺寸设置(单位:厘米)
% ----------------------------------------------
figureUnits = 'centimeters';
figureWidth = 35;
figureHeight = 30;
%% Example 2:饼图填充

figureHandle = figure;
set(gcf, 'Units', figureUnits, 'Position', [0 0 figureWidth figureHeight]); % define the new figure dimensions
colormap(cool(6));
h = pie(rand(6,1));
th = findobj(gca, 'Type', 'text');
set(th, 'FontName', 'Times New Roman', 'FontSize', 12)
hl = legend('Jan','Feb','Mar','Apr','May','Jun');
set(hl,'Box','off','Location','southOutside','NumColumns',3);
set(gca,'Layer','top','FontSize',14,'Fontname', 'Times New Roman');

str= strcat(pathFigure, "Figure3", '.tiff');
print(gcf, '-dtiff', '-r600', str);


im_hatch2 = applyhatch_pluscolor(gcf,'|-.+\/',1,[1 1 0 1 0 0],cool(6),200,3,2);


str= strcat(pathFigure, "Figure4", '.tiff');
print(gcf, '-dtiff', '-r600', str);

参考

1.CSDN博客-matlab画柱状图并填充
2.CSDN博客-matlab画条纹填充(Hatched Fill)图 填坑 applyhatch hardcopy

  • 11
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
MATLAB中,可以使用不同的方法来实现柱状填充。其中一种方法是使用hatchfill2工具,该工具提供了几种不同的填充纹理样式,可以通过在原始堆叠基础添加不同的纹理来解决颜色区分不够而导致的对象识别困难问题\[1\]。另一种方法是使用applyhatch函数,该函数可以在柱状上应用不同的填充纹理样式\[2\]。还有一种方法是使用applyhatch_plusC函数,该函数可以在柱状上应用填充纹理样式,并且可以自定义填充颜色\[3\]。 在具体实现柱状填充时,可以使用bar函数绘制柱状,然后使用text函数在柱状添加数值标签。可以使用grid on函数添加网格线,使用set函数设置X轴显示和y轴名称,使用legend函数设置例。最后,可以使用applyhatch函数或applyhatch_plusC函数对柱状进行填充,选择合适的填充纹理样式\[2\]\[3\]。 请注意,具体的代码实现可能会根据具体需求和数据进行调整。 #### 引用[.reference_title] - *1* *3* [【MATLAB基础绘图第2绘制柱状/饼图填充](https://blog.csdn.net/qq_44246618/article/details/120686376)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [matlab柱状填充](https://blog.csdn.net/u013036495/article/details/93140469)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WW、forever

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值