Matlab —— 基础绘图

本文介绍了MATLAB的基础绘图技巧,包括从数据绘制图形、使用plot函数、控制图层、设置图形风格、添加图例、标题和轴标签、文本与注释、调整图形对象属性、设置轴限制和字体刻度、多图绘制、图形位置大小调整以及保存图形到文件等。
摘要由CSDN通过智能技术生成

基础绘图

  • Basic plotting
  • Graphical object properties

Basic Plotting

Plot from “Data”

Stratagies

  • Generate the numeric values of function over a specific range
  • Display the data “point” in a graphical way

plot()

  • plot( x, y) plots each vector pairs ( x, y)
  • plot( y) plots each vector pairs ( x, y) , where x=[ 1…n], n = length(y)

Example:

>> plot(cos(0:pi/20:2*pi))

这里写图片描述

>> plot(cos(0:pi/20:2*pi));
   plot(sin(0:pi/20:2*pi));

这里写图片描述

由此可见,MATLAB会用新的图像替换旧的图像,cos的图像不会显示出来

hold on / off

Use hold on to have both plots in one figure

hold on
plot(cos(0:pi/20:2*pi));
plot(sin(0:pi/20:2*pi));
hold off

这里写图片描述

Plot Style

  • plot( x , y , ‘str’ ) plots each vector pairs ( x , y ) using the format defined in str

常用:

Data marekersLine typesColors
Cross(×)XSolid line’ — ‘Blackk
Circle(○)ODashed line‘- - ‘Blueb
Plus sign(+)+Dash-dotted line‘-.’Cyanc
Dot(.).Dotted line’ : ‘Greeng
Asterisk(*)*Magentam
Redr
Whitew
Yellowy

- If more polt styles are wanted, please go to the “help” in MATLAB.

hold on
plot(cos(0:pi/20:2*pi),'or');
plot(sin(0:pi/20:2*pi),'*g');
hold off

这里写图片描述

lengend()

Add legend to graph

legend('L1',...)

Position adjustment
放在左上角

legend('L1',...,2)
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,w,'ro-',x,g,'c^-')

这里写图片描述

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,w,'ro-',x,g,'c^-');
legend('sin(x)','cos(x)','Sigmoid','Gauss function');

这里写图片描述

title() & ?label()

title()
xlabel()
ylabel()
zlabel()

x = 0:0.1:2*pi; y1 = sin(x); y2 = exp(-x);
plot(x, y1, '--*', x, y2, ':o');
xlabel('t = 0 to 2\pi');
ylabel('values of sin(t) and e^{-x}')
title('Function Plots of sin(t) and e^{-x}');
legend('sin(t)','e^{-x}');

这里写图片描述

text() & annotation()

Text with mathematical expression using 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]);

这里写图片描述
前后要有 $$.

(‘Interpreter’,’latex’) 不变即可

\int 积分号

_{0} 下界为0
^{2} 上界为2

x^2sin(x) 被积函数

20x2sin(x)dx ∫ 0 2 x 2 sin ⁡ ( x ) d x
去掉反斜 ‘\’
20x2sin(x)dx ∫ 0 2 x 2 s i n ( x ) d x

Figure Adjustment

Several properties:

  • Font
  • Font size
  • Line width
  • Axis limit
  • Tick position
  • Tick label

Graphical Objects

A figure is composed of many objects

  • Figure object
  • Axes object
  • Line object
Created with Raphaël 2.1.2 Start Figures Edit Figure Edit more properties End

Modifying Properties of An Object

Strategy

  • Identify the “handle” of an object
  • Fetch or modify the object’s properties

For example, to change the limits of the x-axis:

  1. Find the handle of the x-axis
  2. Modify the limits

Identifying the Handle of An Object

Upon creantion

h = plot(x,y);

gcf : Figure
gca : Axes
h = plot(x,y) : Line

Utility function

FunctionPurpose
gcareturn the handle of the “current” axes
gcfreturn the handle of the “current” figure
allchildFind all children of specified objects
ancestorFind ancestor of graphics object
deleteDetele an object
findallFind all graphics objects

Fetching or Modifying Properties

to fetch properties
>> get()

to modify properties
>> set()

Getting Object Properties

>> x = linspace(0, 2*pi, 1000);
>> y = sin(x); h = plot(x,y);
>> get(h)
           DisplayName: ''
            Annotation: [1x1 hg.Annotation]
                 Color: [0 0 1]
             LineStyle: '-'
             LineWidth: 0.5000
                Marker: 'none'
            MarkerSize: 6
       MarkerEdgeColor: 'auto'
       MarkerFaceColor: 'none'
                 XData: [1x1000 double]
                 YData: [1x1000 double]
                 ZData: [1x0 double]
          BeingDeleted: 'off'
         ButtonDownFcn: []
              Children: [0x1 double]
              Clipping: 'on'
             CreateFcn: []
             DeleteFcn: []
            BusyAction: 'queue'
      HandleVisibility: 'on'
               HitTest: 'on'
         Interruptible: 'on'
              Selected: 'off'
    SelectionHighlight: 'on'
                   Tag: ''
                  Type: 'line'
         UIContextMenu: []
              UserData: []
               Visible: 'on'
                Parent: 173.0011
             XDataMode: 'manual'
           XDataSource: ''
           YDataSource: ''
           ZDataSource: ''

 >> get(gca)
    ActivePositionProperty = outerposition
    ALim = [0 1]
    ALimMode = auto
    AmbientLightColor = [1 1 1]
    Box = on
    CameraPosition = [3.5 0 17.3205]
    CameraPositionMode = auto
    CameraTarget = [3.5 0 0]
    CameraTargetMode = auto
    CameraUpVector = [0 1 0]
    CameraUpVectorMode = auto
    CameraViewAngle = [6.60861]
    CameraViewAngleMode = auto
    CLim = [0 1]
    CLimMode = auto
    Color = [1 1 1]
    CurrentPoint = [ (2 by 3) double array]
    ColorOrder = [ (7 by 3) double array]
    DataAspectRatio = [3.5 1 1]
    DataAspectRatioMode = auto
    DrawMode = normal
    FontAngle = normal
    FontName = Helvetica
    FontSize = [10]
    FontUnits = points
    FontWeight = normal
    GridLineStyle = :
    Layer = bottom
    LineStyleOrder = -
    LineWidth = [0.5]
    MinorGridLineStyle = :
    NextPlot = replace
    OuterPosition = [0 0 1 1]
    PlotBoxAspectRatio = [1 1 1]
    PlotBoxAspectRatioMode = auto
    Projection = orthographic
    Position = [0.13 0.11 0.775 0.815]
    TickLength = [0.01 0.025]
    TickDir = in
    TickDirMode = auto
    TightInset = [0.0464286 0.0404762 0.00892857 0.0190476]
    Title = [175.001]
    Units = normalized
    View = [0 90]
    XColor = [0 0 0]
    XDir = normal
    XGrid = off
    XLabel = [176.001]
    XAxisLocation = bottom
    XLim = [0 7]
    XLimMode = auto
    XMinorGrid = off
    XMinorTick = off
    XScale = linear
    XTick = [0 1 2 3 4 5 6 7]
    XTickLabel = 
        0
        1
        2
        3
        4
        5
        6
        7
    XTickLabelMode = auto
    XTickMode = auto
    YColor = [0 0 0]
    YDir = normal
    YGrid = off
    YLabel = [177.001]
    YAxisLocation = left
    YLim = [-1 1]
    YLimMode = auto
    YMinorGrid = off
    YMinorTick = off
    YScale = linear
    YTick = [ (1 by 11) double array]
    YTickLabel = [ (11 by 4) char array]
    YTickLabelMode = auto
    YTickMode = auto
    ZColor = [0 0 0]
    ZDir = normal
    ZGrid = off
    ZLabel = [178.001]
    ZLim = [-1 1]
    ZLimMode = auto
    ZMinorGrid = off
    ZMinorTick = off
    ZScale = linear
    ZTick = [-1 0 1]
    ZTickLabel = 
    ZTickLabelMode = auto
    ZTickMode = auto

    BeingDeleted = off
    ButtonDownFcn = 
    Children = [174.002]
    Clipping = on
    CreateFcn = 
    DeleteFcn = 
    BusyAction = queue
    HandleVisibility = on
    HitTest = on
    Interruptible = on
    Parent = [1]
    Selected = off
    SelectionHighlight = on
    Tag = 
    Type = axes
    UIContextMenu = []
    UserData = []
    Visible = on

Setting Axes Limits

>> set(gca,'XLim',[0, 2*pi]);
>> set(gca,'YLim',[-1.2, 1.2]);

这里写图片描述
Alternative

xlim([0, 2*pi]);
ylim([-1.2,1.2]);

Setting Font and Tick of Axes

set(gca,'FontSize', 25);

这里写图片描述

set(gca, 'XTick', 0:pi/2:2*pi);
set(gca, 'XTickLabel',0:90:360);

这里写图片描述

set(gca, 'FontName', 'symbol');
set(gca, 'XTickLabel', {'0', 'p/2', 'p', '3p/2', '2p'});

这里写图片描述

Line Specification

Line style and width
>> set(h, 'LineStyle', '-.','LineWidth', 7.0, 'Color', 'g');

这里写图片描述

Alternative

plot(x, y, '-.g', 'LineWidth', 7.0);

Marker Specification

Face and edge colors of the marker
x = rand(20, 1);  set(gca, 'FontSize', 18);
plot(x, '-md', 'LineWidth', 2, 'MarkerEdgeColor', 'k',...
    'MarkerFaceColor', 'g', 'MarkerSize', 10);
xlim([1, 20]);

这里写图片描述

Multiple Figures

Creak a figure windoe by calling figure
x = -10:0.1:10;
y1 = x.^2 - 8;
y2 = exp(x);
figure, plot(x, y1);
figure, plot(x, y2);

Figure 1Figure 1
Figure 2Figure 2

Be careful when using the gcf handle where there exists multiple figures

Figure Position and Size


figure('Position', [left, bottom, width, height]);

Several Plots in One Figure

Several small plots “in a figure”

subplot(m, n, 1);

m : 纵向个数
n : 横向个数
1 : 先行后列第 1 个

123
456
t = 0: 0.1: 2*pi; x = 3*cos(t); y = sin(t);
subplot(2, 2, 1); plot(x, y); axis normal
subplot(2, 2, 2); plot(x, y); axis square
subplot(2, 2, 3); plot(x, y); axis equal
subplot(2, 2, 4); plot(x, y); axis equal tight

这里写图片描述

Control of Grid, Box and Axis

FunctionDescription
girs on/offMake the grid visible or invisible
box on/offMake the box visible or invisible
axis on/offMake the axes visible or invisible
axis normalAutomatically adjust the aspect ratio of axes and the relative scaling of the data units
axis squalMake the aspect ratio so that the data units are the same in every direction
axis equal tightSet the axis limits to the range of data
axis imageLet the plot box fits tightly around the data
axis ijPlace the origin of the coordinate system in the upper left corner
axis xyPlace the origin in the lower left corner

Saving Figures into Files

saveas(gcf, '<filename>','<formattype>');
OptionBitmap Image Format
‘jpeg’JPEG 24-bit
‘png’PNG 24-bit
‘tiff’TIFF 24-bit(compressed)
‘bmpmono’BMP Monochrome
‘bmp’BMP 24-bit
‘bmp256’BMP 8-bit (256 color, uses a fixed colormap)
OptionVector Graphics Format
‘pdf’Full page Portable Document Format(PDF) color
‘eps’Encapsulated PostScript(EPS) Level 3 black and white
‘epsc’Encapsulated PostScript(EPS) Level 3 color
‘meta’Enhanced Metafile(Windows only)
‘svg’SVG(scalabe vector graphics)
‘ps’Full-page PostScript(PS) Level 3 black and white
‘psc’Full-page PostScript(PS) Level 3 color
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值