MATLAB绘制柱状/饼图填充图

news2025/4/28 9:34:40

MATLAB绘制柱状填充图

  • 方法1:hatchfill2工具
    • 1.1 案例1:柱状图填充
    • 1.2 案例2:饼图填充
  • 方法2:applyhatch函数
    • 2.1 案例1:柱状图填充
    • 2.2 案例2:饼图填充
  • 方法3: applyhatch_plusC函数
    • 3.1 案例1:柱状图填充
    • 3.2 案例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);

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/414066.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Python 小型项目大全 31~35

三十一、猜数字 原文&#xff1a;http://inventwithpython.com/bigbookpython/project31.html 猜数字是初学者练习基本编程技术的经典游戏。在这个游戏中&#xff0c;电脑会想到一个介于 1 到 100 之间的随机数。玩家有 10 次机会猜出数字。每次猜中后&#xff0c;电脑会告诉玩…

Java实现ArrayList和底层源码讲解

&#x1f389;&#x1f389;&#x1f389;点进来你就是我的人了 博主主页&#xff1a;&#x1f648;&#x1f648;&#x1f648;戳一戳,欢迎大佬指点!人生格言&#xff1a;当你的才华撑不起你的野心的时候,你就应该静下心来学习! 欢迎志同道合的朋友一起加油喔&#x1f9be;&am…

Centos7安装MySQL5.7.30

文章目录1. 环境准备1.1 卸载mariadb1.2 下载MySQL 5.7.301.3 安装MySQL依赖项1.4 创建目录1.5 创建用户和用户组1.6 修改Mysql用户权限2. 安装MySQL2.1 解压2.2 修改解压目录名称2.3 初始化2.4 添加my.cnf异常找不到Sock文件2.5 启动MySQL服务2.5.1 建立软连接2.5.2 启动2.6 设…

TCP协议工作机制二(滑动窗口,流量控制,拥塞控制,延时应答,捎带应答等)

目录 滑动窗口 流量控制 拥塞控制 延时应答 捎带应答 面向字节流 异常情况 UDP和TCP对比 滑动窗口 由于TCP是可靠传输,有确认应答,超时重传,连接管理等机制,发送消息时需要等待接收方返回的ack.因此会消耗大量等待ack的时间,我们引入滑动窗口的机制来竭尽可能提高TCP的…

基于支持向量机的Digits手写数字识别

基于支持向量机的Digits手写数字识别 描述 支持向量机&#xff08;Support Vector Machine&#xff0c;简称SVM&#xff09;模型既可以用于分类也可以用于回归。手写数字识别是一个多分类问题&#xff08;判断一张手写数字图片是0~9中的哪一个&#xff09;&#xff0c;数据集…

图片英文翻译成中文转换器-中文翻译英文软件

您正在准备一份重要的英文资料或文件&#xff0c;但是您还不是很熟练地掌握英文&#xff0c;需要翻译才能完成您的任务吗&#xff1f;哪个软件能够免费把英文文档翻译成中文&#xff1f;让我们带您了解如何使用我们的翻译软件来免费翻译英文文档为中文。 我们的翻译软件是一款功…

C风格的字符串赋值方式

文章目录&#xff08;1&#xff09;C语言中&#xff0c;没有字符串类型但可以用字符数组模拟字符串。&#xff08;2&#xff09;C语言中&#xff0c;字符串是以’\0’作结尾字符。&#xff08;3&#xff09;C语言中&#xff0c;字符串常量本质上是一个无名的字符数组。C风格的字…

使用Spring JDBC中的JdbcTemplate对数据进行增删改查操作教程~

jdbcTemplate实现添加数据功能&#xff1a; spring框架对jdbc框架进行封装&#xff0c;使用jdbcTemplate方便实现对数据库的操作 数据库准备工作&#xff1a; 在已有数据库中创建新的表&#xff1a; create table t_user (id int,username varchar(20),password varchar(20…

搜索词分析工具-网站关键词挖掘

怎么能找到行业的关键词 以下是如何找到行业关键词的建议&#xff1a; 了解行业&#xff1a;要找到与行业相关的关键词&#xff0c;首先需要了解行业。了解行业以及核心目标&#xff0c;从而更好地理解行业中的主题和词汇。 找到竞争对手网站&#xff1a;搜索竞争对手的网站&…

k8s部署Dashboard

k8s和Dashboard的版本对应关系可以到Dashbord的对应版本里看&#xff0c;比如这里&#xff1a; https://github.com/kubernetes/dashboard/releases/tag/v2.7.0 以下步骤都是在master上执行的。 1. 部署步骤 1. 获取Dashbord的yaml文件 wget https://raw.githubusercontent…

【Git】—— 如何安装Git及简单使用

Git是一个开源的分布式版本控制工具&#xff0c;可以更好地管理你的项目。 一、Linux操作系统 如果用的是Ubuntu系统&#xff0c;只需打开shell界面&#xff0c;输入&#xff1a; sudo apt-get install git-core 按下回车即可完成安装。 二、Windows操作系统 Windows操作系统不…

C语言-数据结构与算法-详细全面的链表知识总结归纳

C语言链式存储结构的详细讲解一.前言(为什么要使用链式存储)一.单链表1.单链表的结点描述2.单链表基本操作(1)初始化单链表(2)采用头插法建立单链表(带头结点)(3).采用尾插法建立单链表(4)按照位序查找结点(4)在链表中间插入结点(5)删除第i个结点二.双链表1.双链表的结点类型描…

和ChatGPT-4聊完后,我觉得一切可能已经来不及了

了然无味&#xff0c;晴空万里&#xff01;和ChatGPT-4开始了一场坦诚的沟通&#xff0c;它全程都表现出高情商&#xff0c;以及不断尽量安抚我的情绪&#xff0c;而这&#xff0c;恰恰令我脊背发凉。 部分文字截取 ZM&#xff1a;我能不能理解每次对话就是一次你的“生命” G&…

【Android -- 软技能】分享一个学习方法

前言 很多人都想通过学习来提升自己&#xff0c;但是&#xff0c;可能因为两个问题&#xff0c;阻碍了自己的高效提升&#xff1a; 学什么&#xff1f; 怎么学&#xff1f; 本文将从自己的学习实践出发&#xff0c;针对这两个问题&#xff0c;给出自己的一套学习流程。 1…

免费集装箱号识别API免费集装箱信息识别,中国人工智能企业CIMCAI集装箱识别云服务全球4千企业用户,中国人工智能企业智慧港航

免费集装箱号识别API免费集装箱信息识别API&#xff0c;CIMCAI飞瞳引擎™集装箱人工智能平台全球4千企业用户&#xff0c;全球领先的飞瞳引擎™AI集装箱识别云服务&#xff0c;集装箱残损识别箱况检测缺陷检验&#xff0c;小程序拍照检测或支持API接口二次开发&#xff0c;应用…

00后整顿职场,我直呼太卷了....

内卷的来源 内卷最早的“出处”是几张名校学霸的图片。 大学生们刷爆朋友圈的几张“内卷”图片是这样的&#xff1a;有的人骑在自行车上看书&#xff0c;有的人宿舍床上铺满了一摞摞的书&#xff0c;有的人甚至边骑车边端着电脑写论文。这些图片最早在清华北大的学霸之间流传。…

AI工具究竟是帮手还是对手?对此你怎么看,一起来聊聊你的看法吧!

© Ptw-cwl 前言 AI工具既可以是帮手&#xff0c;也可以是对手&#xff0c;这取决于我们如何使用它们。 如果我们正确地利用AI工具&#xff0c;它们可以为我们带来很多好处&#xff0c;例如更快的数据分析、更准确的预测和更高效的决策。然而&#xff0c;如果我们滥用AI工…

嵌入式开发:硬件和软件越来越接近

从前&#xff0c;硬件和软件工程师大多生活在自己的世界里。硬件团队设计了芯片&#xff0c;调试了从铸造厂返回的第一批样本&#xff0c;让软件团队测试他们的代码。随着虚拟平台和其他可执行模型变得越来越普遍&#xff0c;软件团队可以在芯片制造之前开始&#xff0c;有时甚…

贝叶斯优化 | BO-RF贝叶斯优化随机森林多输入单输出回归预测(Matlab完整程序)

贝叶斯优化 | BO-RF贝叶斯优化随机森林多输入单输出回归预测(Matlab完整程序) 目录 贝叶斯优化 | BO-RF贝叶斯优化随机森林多输入单输出回归预测(Matlab完整程序)预测结果基本介绍评价指标程序设计参考资料预测结果 基本介绍 贝叶斯优化 | BO-RF贝叶斯优化随机森林多输入单…

面试题

用 C写一个函数&#xff0c;交换两个整型变量 int a 5, b 10; cout << "Before swapping: a " << a << ", b " << b << endl; swapVars<int>(a, b); cout << "After swapping: a " << a …