Matlab: 作图-程序员宅基地

技术标签: matlab  

查看当前变量可以用who,查看当前变量及其结构,大小,类型等,可以用whos。

  1. 控制图的大小
figure(‘position’,[x0,y0,dx,dy]);
figure(fig number);
  1. 控制图例(legend)
legend('leg1','leg2','Location','NorthWest');
% hide the legend box
legend boxoff
% set the color of the legend is done via latex grammar
legend('\color{red}leg1','\color{blue}leg2');
% use RGB color value in legend
legend('\color[rgb]{1,1,0}');

depend on how many lines you plot in a figure;
控制图例的相对位置

figure();
sub(1)=subplot(2,1,1);
plot(x1,y1);
leg(1)=legend('f1');
sub(2)=subplot(2,1,2);
plot(x2,y2);
leg(2)=legend('f2');
% control the relative position of legend in whole figure
leg(1).Position=[x1,y1,dx1,dy1];
leg(2).Position=[x2,y2,dx2,dy2];
  1. 改变字体大小
    change the fontsize of x,y label at the same time.
set(gca,'fontsize',15)
  1. 显示小刻度
% show minor tick on x axis
set(gca,'XMinorTick','on');
% show minor tick on y axis
set(gca,'YMinorTick','on');
  1. 设置线条宽度
set(gca,'LineWidth',2);
  1. 支持Latex语法
% in xlabel, ylabel and title, you can use latex code directly 
xlabel('\frac{\pi x^2}{\sqrt(y+3)}');
% but for legend, the case is a little different, you should use cell, $$ symbol and 'interpreter'
legend({'$\frac{\pi x^2}{\sqrt(y+3)}$'},'interpreter','latex'));
  1. 从fig格式的图中读取数据
    matlab中的图可以保存成fig格式,可以自由地进行编辑,有时我们还希望可以从fig文件中读取出数据,可以使用下面的代码:
h=open('data.fig');
x=h.Children.Children.XData;
y=h.Children.Children.YData;
fig1=figure();
plot(x,y);

如果图是通过subplot生成的多个子图拼成的,则提取数据的过程还会更复杂些。例如一个:subplot(2,1,:)的图。

clear all;close all;clc;
subdata=openfig('data_subplot.fig');
x1=subdata.Children(1).Children.XData;
y1=subdata.Children(1).Children.YData;
x2=subdata.Children(2).Children.XData;
y2=subdata.Children(2).Children.YData;
figure()
plot(x1,y1,x2,y2);
title('extracted data from subplot fig file');

如果字图中的曲线多于一条,最底层的Children还会再多些,但是基本的思路是类似的,同样可以从中读出数据,例如代码可能是这样的:

y21=subdata.Children(2).Children(1).YData;
y22=subdata.Children(2).Children(2).YData;
  1. 获知图的信息
    在matlab中,图是一个结构体对象,可以用get(fig1)的方式来查看其对象。

  2. 使用对数坐标[1]
figure()
plot(x,y);
% set the x axis as log scale, same operation for x axis
set(gca, 'YScale', 'log');
% to convert it back to normal axis, you can use linear scale
set(gca, 'YScale','linear');
  1. stem[2]
    stem(x,y)可以画出像毛草一样的效果,对于展示信号的振幅非常直观,如下图。
x=0:0.1:1;
figure();
stem(x,sin(x));

985636-20170629191544711-1026722747.png

  1. 保存fig图
fig0=figure();
plot(x,y);
savefig(fig0,'picture.fig');
  1. 绘制双Y轴坐标图
[ax h1 h2] = plotyy(x1,y1, x2,y2);
axes(ax(1)); ylabel('First y-label');
axes(ax(2)); ylabel('Second y-layel');

yyaxis替代plotyy

fig = figure;
left_color = [.5 .5 0];
right_color = [0 .5 .5];
set(fig,'defaultAxesColorOrder',[left_color; right_color]);
yyaxis left
ax1=plot(x1,y1);
yyaxis right
ax2=plot(x2,y2);
% yyaxis中ylim的设置
ax=get(gca);
ax.YAxis(1).Ylimits=[0,300];
ax.YAxis(2).Ylimits=[0,3];

在subplot子图中可以这样设置

% this will the set the color of Y axis
sub(2).YAxis(1).Color=[0,0,1]% blue
sub(2).YAxis(2).Color=[1,0,0]% red
  1. 绘图2D, pcolor
x=(0:0.1:2);% 1*20
y=(0:0.2:1)';% 5*1
yx=y*x;% 5*20
figure();
pcolor(x,y,yx);
shading flat;% smooth the color edge
xlabel('x');
ylabel('y');
colorbar();
title('pcolor');
  1. 绘图2D, contourf
figure();
contourf(x,y,yx,'edgecolor','none');
colorbar;
xlabel('x');
ylabel('y');
title('contourf');
985636-20170708115020019-515353619.png 985636-20170708115034706-112652917.png

在绘制二维谱图的过程中,默认的设置会覆盖掉X,Y轴的刻度点,要使其显示出来,可以使用以下设置。

set(gca,'Layer','top');
  1. 分段函数的快速绘制
f_test=@(x)( (x<=1)*0 + (x>1&x<2).*(x+2) + (x>=0)*0 );
x_test=0:0.1:5;
y_test=f_test(x_test);
figure();
plot(x_test,y_test);

985636-20170708185143456-1955927732.png

  1. 给坐标添加文字注释[3]
    text(x0,y0,'text');
    这种方式是针对axis对象进行的注释因而可以在subplot中方便地使用,而annotation则是针对fiugure进行的注释,因而在subplot中的使用多有不便。

  2. Matlab 图形对象
    gca: 获得当前axes对象
    gcf: 获得当前figure对象

  3. 图中添加文本注释[4]
% test colorbar position
clear all;close all;clc;
x=linspace(3,5,200);
y=sin(x);
% text annotation to a specific data point
fig1=figure();
x0=3:0.01:4;
y0=cos(x0);
plot(x0,y0,'-*');
text(x0(50),y0(50),'test','Color','red');
% text annotation to a relative position on figure
figure();
fig1=subplot(2,1,1);
plot(x,sin(2*pi*90*x));
set(gca,'fontsize',15,'linewidth',1.5);
text1=annotation('TextBox',[0.2,0.8,0.05,0.05],'String','(a)','FontSize',15,'Color','blue','EdgeColor','none');
fig2=subplot(2,1,2);
set(gca,'fontsize',15,'linewidth',1.5);
ax2=plot(x,x);
text2=annotation('TextBox',[0.2,0.4,0.05,0.05],'String','(b)','FontSize',15,'Color','red','EdgeColor','none');
  1. 设定subplot子图和colorbar的位置
    可以通过控制每个字图的位置得到比较紧凑的绘图效果,这个主要是通过控制图形对象的位置来实现。
% test colorbar position
clear all;close all;clc;
x=linspace(0,1,100);
y=sin(x);
figure();
fig1=subplot(2,1,1);
plot(x,y);
bar1=colorbar();
% hide the value tick on colorbar
set(bar1,'XTickLabel',[]);
legend('sub1');
fig2=subplot(2,1,2);
plot(x,x);
legend('sub2');
% fig.position=[x0,y0,dx,dy]
fig1.Position=[0,0.5,0.5,0.5];
bar1.Position=[0.5,0.5,0.2,0.5];
fig2.Position=[0.5,0,0.5,0.5];

985636-20170724165452371-497138170.png

  1. remove xtick label
sub=subplot(3,1,1)
plot(x,y);
set(sub,'XTickLabel',[]);
  1. 定制自己的colormap
% custom my colormap for spectrum display
mymap=zeros(7,3);
mymap(7,:)=[139,000,000];% dark red  
mymap(6,:)=[255,000,000];% red          
mymap(5,:)=[255,127,000];% orange
mymap(4,:)=[255,255,000];% yellow
mymap(3,:)=[000,255,000];% green
% mymap(3,:)=[000,255,255];% cyan 青色
mymap(2,:)=[000,000,255];% blue
mymap(1,:)=[255,255,255];% white      
% normalize the color map RGB values to within [0,1]
mymap=mymap/255;

经过这样的定制之后,既可以在绘图时直接使用这个colormap了,在绘制二维图时调用的语法是colormap(mymap),注意colormap的顺序也是按照数组中从上到下的的顺序排列的。当然还可以利用二维插值,把colormap的颜色加密后使用。
985636-20170726163012734-1503187668.png
补充:matlab default color names and related RGB values

Black        0  0  0 黑
Blue         0  0  1 蓝
Cyan        0  1  1 青
Green      0  1  0 绿
Magenta  1  0  1 紫红
Red         1  0  0 红
White      1  1  1 白
Yellow     1  1  0 黄

在subplot中对不同的子图设置不同的colormap和colorbar,这里的操作只适合于新版的matlab(2015R之后)。在新版的matlab中可以在每个子图里使用set(gca,colormap_n)来控制对应的colormap,而colorbar则会随着colormap的不同而自动调整。

  1. 更改x,y Ticks的颜色
set(gca,'xcolor','red','ycolor','green');
  1. 避免subplot中坐标轴标号重叠 (Axis Tick label overlap)
    这个没有什么灵丹妙药,最有效的方式是通过手工调整ylim的范围,通过合适的选择可以避免上下两个子图y坐标标号的重叠。
sub(1).YLim=[y1,y2];
sub(2).YAxis(1).Limits=[z11,z12];
sub(2).YAixs(2).Limits=[z21,z22];

以上,sub(1)是单轴的子图,sub(2)是双轴的子图。

  1. 控制线条的颜色,格式和粗细大小[5]
figure()
plot(x,y,'--green');
plot(x2,y2,'color',[1,0,0],'LineStyle','--');

matlab可直接调用的颜色名称如前colormap的附录,对于其他颜色,可以通过归一化的RGB参数来调用。可直接调用的线条格式如下:

% line styles
'-'     Solid line (default)
'--'    Dashed line
':' Dotted line
'-.'    Dash-dot line
% line marker styles
 '+'    Plus sign
'o' Circle
'*' Asterisk
'.' Point
'x' Cross
'square' or 's'         Square
'diamond' or 'd'      Diamond
'^' Upward-pointing triangle
'v'     Downward-pointing triangle
'>' Right-pointing triangle
'<' Left-pointing triangle
'pentagram' or 'p'     Five-pointed star (pentagram)
'hexagram' or 'h'      Six-pointed star (hexagram)

控制marker的大小以及填充颜色

plot(f_TAE_eqs,f_exp_eqs,'o blue','MarkerSize',9,'MarkerFaceColor','blue');
  1. 插入箭头注释
% add an arrow in figure
hold on
Ar1= annotation('arrow');
Ar1.X=[0.37,0.65];
Ar1.Y=[0.42,0.48];
Ar1.LineWidth=2;
Ar1.LineStyle='--';
Ar1.Color='red';

上面的代码控制了箭头注释在整个fig图中的相对位置。

  1. 控制坐标轴刻度线的长短和粗细
% change TickLength of current axis, former is minor TickLength, later is major TickLength 
set(gca,'TickLength',[0.03,0.06]);
% change the Tick width of current axis
set(gca,'LineWidth',1.5);
  1. 控制图形边框的有无
    可以通过box参数简单地控制图形边框的显示与否[6]
% show figure black border
set(gca,'box','on');
% hide figure black border
set(gca,'box','off');
  1. 控制colorbar的显示范围
    在图中可以类似于xlim,ylim一样用caxis([low,high])来手工设定。
  2. 图中添加高亮透明色块[7][8]
hold on
ha = area([51, 164],[30,30],'FaceColor','red','FaceAlpha',0.1,'Edgecolor','none');

其中area的前两个参数[x1,x2],[y1,y2]确定了色块在图中的位置,而FaceColor确定了颜色的类型,而FaceAlpha则确定了色块的透明度,Edgecolor则确定了色块边框的颜色。

  1. 添加垂直的竖线
t2=3.3;
t3=4.8;
hold on
line([t3,t2],[0,100],'Color',c3,'LineStyle','-.','LineWidth',2);

这个可以用line函数简单地实现,第一组参数是x轴坐标,第二组参数是y轴范围。当然如果你不怕麻烦,也可以自己写出需要的数列,直接用plot来完成。

  1. 论文中contour图colormap范围的调节技巧
    要让两幅图实现类似的色彩效果,首先要调节colorbar的底色,等到最低的背景色基本相同的时候,再调节最强幅度对应的颜色,这样两幅图的风格比较类似了。
  2. 格点线(grid on)的设置
% test grid line style control
clear all;close all;clc;
x=0:100;
y=sin(0.1*x);
figure('Position',[0,0,600,500]);
plot(x,y);
xlabel('x');
ylabel('y');
title('test grid style');
grid on;
set(gca,'FontSize',15,'Linewidth',1.5);
set(gca,'XMinorTick','on','YMinorTick','on');% control on/off of minor grids
set(gca, 'xminorgrid', 'on','YMinorGrid','on');% control on/off of minor grid lines
set(gca,'MinorGridLineStyle',':');% set minor grid line style
set(gca,'GridLineStyle','--');% set major grid line style
set(gca,'GridAlpha',0.3);% set grid line transparence

985636-20180116110448490-1961724900.png

参考:
[1]https://cn.mathworks.com/matlabcentral/answers/279106-how-to-set-y-axis-as-log-scale
[2]https://stackoverflow.com/questions/23322565/plot-a-peak-with-height
[3]https://cn.mathworks.com/help/matlab/creating_plots/add-text-to-specific-points-on-graph.html
[4]https://stackoverflow.com/questions/14262354/textbox-in-matlab-plot
[5]https://cn.mathworks.com/help/matlab/ref/linespec.html
[6]https://stackoverflow.com/questions/9166786/remove-border-around-matlab-plot
[7]https://stackoverflow.com/questions/4698679/shading-between-vertical-lines-in-matlab
[8]https://cn.mathworks.com/help/matlab/ref/area.html

转载于:https://www.cnblogs.com/docnan/p/5673883.html

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_34413357/article/details/94477239

智能推荐

攻防世界_难度8_happy_puzzle_攻防世界困难模式攻略图文-程序员宅基地

文章浏览阅读645次。这个肯定是末尾的IDAT了,因为IDAT必须要满了才会开始一下个IDAT,这个明显就是末尾的IDAT了。,对应下面的create_head()代码。,对应下面的create_tail()代码。不要考虑爆破,我已经试了一下,太多情况了。题目来源:UNCTF。_攻防世界困难模式攻略图文

达梦数据库的导出(备份)、导入_达梦数据库导入导出-程序员宅基地

文章浏览阅读2.9k次,点赞3次,收藏10次。偶尔会用到,记录、分享。1. 数据库导出1.1 切换到dmdba用户su - dmdba1.2 进入达梦数据库安装路径的bin目录,执行导库操作  导出语句:./dexp cwy_init/[email protected]:5236 file=cwy_init.dmp log=cwy_init_exp.log 注释:   cwy_init/init_123..._达梦数据库导入导出

js引入kindeditor富文本编辑器的使用_kindeditor.js-程序员宅基地

文章浏览阅读1.9k次。1. 在官网上下载KindEditor文件,可以删掉不需要要到的jsp,asp,asp.net和php文件夹。接着把文件夹放到项目文件目录下。2. 修改html文件,在页面引入js文件:<script type="text/javascript" src="./kindeditor/kindeditor-all.js"></script><script type="text/javascript" src="./kindeditor/lang/zh-CN.js"_kindeditor.js

STM32学习过程记录11——基于STM32G431CBU6硬件SPI+DMA的高效WS2812B控制方法-程序员宅基地

文章浏览阅读2.3k次,点赞6次,收藏14次。SPI的详情简介不必赘述。假设我们通过SPI发送0xAA,我们的数据线就会变为10101010,通过修改不同的内容,即可修改SPI中0和1的持续时间。比如0xF0即为前半周期为高电平,后半周期为低电平的状态。在SPI的通信模式中,CPHA配置会影响该实验,下图展示了不同采样位置的SPI时序图[1]。CPOL = 0,CPHA = 1:CLK空闲状态 = 低电平,数据在下降沿采样,并在上升沿移出CPOL = 0,CPHA = 0:CLK空闲状态 = 低电平,数据在上升沿采样,并在下降沿移出。_stm32g431cbu6

计算机网络-数据链路层_接收方收到链路层数据后,使用crc检验后,余数为0,说明链路层的传输时可靠传输-程序员宅基地

文章浏览阅读1.2k次,点赞2次,收藏8次。数据链路层习题自测问题1.数据链路(即逻辑链路)与链路(即物理链路)有何区别?“电路接通了”与”数据链路接通了”的区别何在?2.数据链路层中的链路控制包括哪些功能?试讨论数据链路层做成可靠的链路层有哪些优点和缺点。3.网络适配器的作用是什么?网络适配器工作在哪一层?4.数据链路层的三个基本问题(帧定界、透明传输和差错检测)为什么都必须加以解决?5.如果在数据链路层不进行帧定界,会发生什么问题?6.PPP协议的主要特点是什么?为什么PPP不使用帧的编号?PPP适用于什么情况?为什么PPP协议不_接收方收到链路层数据后,使用crc检验后,余数为0,说明链路层的传输时可靠传输

软件测试工程师移民加拿大_无证移民,未受过软件工程师的教育(第1部分)-程序员宅基地

文章浏览阅读587次。软件测试工程师移民加拿大 无证移民,未受过软件工程师的教育(第1部分) (Undocumented Immigrant With No Education to Software Engineer(Part 1))Before I start, I want you to please bear with me on the way I write, I have very little gen...

随便推点

Thinkpad X250 secure boot failed 启动失败问题解决_安装完系统提示secureboot failure-程序员宅基地

文章浏览阅读304次。Thinkpad X250笔记本电脑,装的是FreeBSD,进入BIOS修改虚拟化配置(其后可能是误设置了安全开机),保存退出后系统无法启动,显示:secure boot failed ,把自己惊出一身冷汗,因为这台笔记本刚好还没开始做备份.....根据错误提示,到bios里面去找相关配置,在Security里面找到了Secure Boot选项,发现果然被设置为Enabled,将其修改为Disabled ,再开机,终于正常启动了。_安装完系统提示secureboot failure

C++如何做字符串分割(5种方法)_c++ 字符串分割-程序员宅基地

文章浏览阅读10w+次,点赞93次,收藏352次。1、用strtok函数进行字符串分割原型: char *strtok(char *str, const char *delim);功能:分解字符串为一组字符串。参数说明:str为要分解的字符串,delim为分隔符字符串。返回值:从str开头开始的一个个被分割的串。当没有被分割的串时则返回NULL。其它:strtok函数线程不安全,可以使用strtok_r替代。示例://借助strtok实现split#include <string.h>#include <stdio.h&_c++ 字符串分割

2013第四届蓝桥杯 C/C++本科A组 真题答案解析_2013年第四届c a组蓝桥杯省赛真题解答-程序员宅基地

文章浏览阅读2.3k次。1 .高斯日记 大数学家高斯有个好习惯:无论如何都要记日记。他的日记有个与众不同的地方,他从不注明年月日,而是用一个整数代替,比如:4210后来人们知道,那个整数就是日期,它表示那一天是高斯出生后的第几天。这或许也是个好习惯,它时时刻刻提醒着主人:日子又过去一天,还有多少时光可以用于浪费呢?高斯出生于:1777年4月30日。在高斯发现的一个重要定理的日记_2013年第四届c a组蓝桥杯省赛真题解答

基于供需算法优化的核极限学习机(KELM)分类算法-程序员宅基地

文章浏览阅读851次,点赞17次,收藏22次。摘要:本文利用供需算法对核极限学习机(KELM)进行优化,并用于分类。

metasploitable2渗透测试_metasploitable2怎么进入-程序员宅基地

文章浏览阅读1.1k次。一、系统弱密码登录1、在kali上执行命令行telnet 192.168.26.1292、Login和password都输入msfadmin3、登录成功,进入系统4、测试如下:二、MySQL弱密码登录:1、在kali上执行mysql –h 192.168.26.129 –u root2、登录成功,进入MySQL系统3、测试效果:三、PostgreSQL弱密码登录1、在Kali上执行psql -h 192.168.26.129 –U post..._metasploitable2怎么进入

Python学习之路:从入门到精通的指南_python人工智能开发从入门到精通pdf-程序员宅基地

文章浏览阅读257次。本文将为初学者提供Python学习的详细指南,从Python的历史、基础语法和数据类型到面向对象编程、模块和库的使用。通过本文,您将能够掌握Python编程的核心概念,为今后的编程学习和实践打下坚实基础。_python人工智能开发从入门到精通pdf