Skip to content

Instantly share code, notes, and snippets.

@zhulianhua
Last active September 2, 2016 16:28
Show Gist options
  • Save zhulianhua/7761c994303284d91585 to your computer and use it in GitHub Desktop.
Save zhulianhua/7761c994303284d91585 to your computer and use it in GitHub Desktop.

###Matlab 绘图教程

如何查看帮助

  • 简单帮助用 help命令, 如 查看 contourf 的用法可以用help contourf
  • 详细帮助用doc命令, 如查看plot的用法可以用doc contourf

####一个比较完全的示例

x = 0:0.1:2*pi;
y1 = sin(x);
y2 = cos(x);

% 画线,参考后文线型设置
plot(x,y1, 'r-^', x,y2,'bo-.','linewidth',2, 'markersize',8);

% 设置坐标轴属性,如刻度的字体、字号, gca代表当前坐标轴
set(gca,'fontsize',16,'fontname','Times New Roman');

% 左右上下都有坐标轴
box on;
% 设置x/y轴上的label。
xlabel('$x$', 'Interpreter','latex','fontsize',18);
ylabel('$\sin(x)/\cos(x)$', 'Interpreter','latex','fontsize',18);

%设置图例
leg = legend('$y_1$','$y_2$');
set(leg,'Interpreter','latex','fontsize',18,...
   'location','north','box', 'off','orientation', 'horizontal','Position',[0.1,0.2,0.4,0.3]);
   
注意,如果legend entries太挤了,调整Position的后面连个参数(widht, heidht)可以改变lengend box的大小,让间距变大些


%设置绘图范围,即坐标轴刻度范围
axis([0, 2*pi, -1,1.2]);
%或者
xlim([0,5]);
%或者
ylim([1,100]);

%设置图形的位置和长宽及背景色。
%200,200表示图形左下角距离屏幕左下角的水平距离和竖直距离。
%600,400表示图形的长、宽,单位是点
%背景色是白色, white (w)
set(gcf,'Position',[200,200,600,400],'color','w');
%可以通过如下方式使用其他单位来设置figure的尺寸和位置:
fig1.Units='inches'; fig1.Position = [2,2,6,5];

%保存彩色eps图片,文件名为xy.eps。epsc表示带颜色的eps文件, 可以换成png或者jpg。
saveas(gcf, 'xy','epsc');

####选择控制的图形(figure)

有时候用figure产生几个图,要选择操作哪个图可以用图的名字指定。图的名字可以在调用figure时指定,如下面的fig1fig2:另外gcf表示当前被控制的图。

fig1 = figure(); %此后gcf就是fig1
fig2 = figure(); %此后gcf就是fig2
set(fig1,'Position',[200,200,400,400],'color','w');
set(fig2,'Position',[700,200,300,400],'color','w');

不过更好的建议是画完一个图就关掉一个图,每次处理一个图就好了。 关掉当前的图可以用close(gcf)。可以用figure名字指定关掉哪个图,如close(fig2).

####线型设置 颜色、线性、marker三者的组合设置,用一个字符串表示如'r-o'表示红色(red)实线(-),marker是圈圈(o),再如'b--s'表示蓝色(blue)虚线(--),marker是方块(square)。所有的线性组合类型可以通过doc plot 查看

####图例设置

####设置tick的数字格式:

x=[1 1.53 4];
y=[1 2 3];
plot(x,y)
set(gca,'XTick',x)
set(gca,'XTickLabel',sprintf('%3.4f|',x))
set(gca,'YTick',y)
set(gca,'YTickLabel',sprintf('%+1.2f|',y))

####设置tick,参考

ax = gca;
ax.XTick = [-3*pi -2*pi -pi 0 pi 2*pi 3*pi];
ax.YTick = [-1 -0.5 0 0.5 1];

####logscale set(gca,'YScale','log');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment