基础绘图
- matlab无法直接根据函数表达式画图;
- 先生成数值点,再根据数据绘图。
plot()
plot(x,y)
:画出每个点(x,y)
plot(y)
:画出每个点(x=[1…n],n=length(y))
Example:
>> plot(cos(0:pi/20:2*pi))
同时保留多个图形
matlab会自动覆盖上一个图形,如果需要保留多个图形,需要用到hold on
指令。
>> hold on
>> plot(cos(0:pi/20:2*pi));
>> plot(sin(0:pi/20:2*pi));
>> hold off
也可以先给变量和函数赋值,再一起使用plot
绘图
plot style 格式设定
plot(x,y,'str')
:使用字符串对应的格式来绘图,详见下表
legend()
在图形中加入图例:
Legend('L1',...)
>> x=0:0.5:4*pi;
>> y=sin(x); h=cos(x); w=1./(1+exp(-x));
>> g=(1/(2*pi*2)^0.5).*exp((-1.*(x-2*pi).^2)./(2*2^2));
>> plot(x,y,'bd-',x,h,'gp:',x,g,'c^-',x,w,'ro-')
>> legend('sin(x)','cos(x)','Guass Function','Sigmoid')
注:在legend()
中添加‘Location’,'方位名'
可以改变图例的位置
添加title或坐标轴名称
- title()
- xlabel()
- ylabel()
- zlabel()
>> x=0:0.1:2*pi;y1=sin(x);y2=exp(-x);
>> plot(x,y1,'--*',x,y2,':o');
>> xlabel('x= 0 to 2\pi');
>> ylabel('Values of sin(x) and e^{-x}');
>> title('Fuction plots of sin(x) and e^{-x}');
>> legend('sin(x)','e^{-x}');
注:
- \pi 代表字符pai的意思,显示为π;
- 当指数为一串字符时,用
{}
括起来
(此处实为latex语法)
text() & annotation()
-
text()函数用来给图加上说明性文字。
格式:text(x,y,'txt')
或者:text(x,y,'txt','color','k')
-
用latex语法来显示字符串内容
text(x,y,'txt','Interpreter','latex')
>> x=linspace(0,3); y=x.^2.*sin(x); plot(x,y);
>> line([2,2],[0,2^2*sin(2)]);
>> str='$$\int_{0}^{2} x^2\sin(x) dx $$';
>> text(0.25,2.5,str,'Interpreter','latex');
>> annotation('arrow','X',[0.32,0.5],'Y',[0.6,0.4]);
- annotation()用来给图加上箭头或标注
语法 | 用途 |
---|---|
annotation(annotation_type) | 以指定的对象类型,使用默认属性值建立注释对象 |
annotation(‘line’,x,y) | 建立从(x(1), y(1))到(x(2), y(2))的线注释对象。 |
annotation(‘arrow’,x,y) | 建立从(x(1), y(1))到(x(2), y(2))的箭头注释对象。 |
annotation(‘doublearrow’,x,y) | 建立从(x(1), y(1))到(x(2), y(2))的双箭头注释对象 |
annotation(‘textarrow’,x,y) | 建立从(x(1),y(1))到(x(2),y(2))的带文本框的箭头注释对象。 |
annotation(‘ellipse’,[x y w h]) | 建立椭圆形注释对象。 |
annotation(‘rectangle’,[x y w h]) | 建立矩形注释对象。 |
注:这里的x,y指的是占整个图形的比例,而非对应坐标轴的具体值。
- Exercise:
t=linspace(1,2); f=t.^2; g=sin(2*pi.*t);
plot(t,f,'-k',t,g,'or');
xlabel('Time(ms)'); ylabel('f(t)');title('Mini assignment#1');
legend('t^{2}','sin(2\pit)','Location','northwest');
修改图形属性
包括图形、线条、tick等元素,此处与origin类似,进入编辑器需要修改哪里就点击哪里。
以下为通过指令来修改具体属性,使用时需要注意区分不同的对象。
1. 定义对象的辨识码(handle)
>> x=linspace(0,2*pi,1000); y=sin(x);
>> plot(x,y); set(gcf,'Color',[1,1,1]);
>> h=plot(x,y);
得到(x,y)线条的辨识码h
。
- 相关效用函数:
函数名 | 用途 |
---|---|
gca | 返回现有坐标轴的指针 |
gcf | 返回现有图形的指针 |
allchild | 找到指定对象的所有子级 |
ancestor | 找到图形对象的父级 |
delete | 删除一个对象 |
findall | 找到所有图形对象 |
2. 得到对象的属性:get()
>> h=plot(x,y);
>> get(h)
AlignVertexCenters: 'off'
Annotation: [1x1 matlab.graphics.eventdata.Annotation]
BeingDeleted: 'off'
BusyAction: 'queue'
ButtonDownFcn: ''
Children: [0x0 GraphicsPlaceholder]
Clipping: 'on'
Color: [0 0.4470 0.7410]
%后续省略
</