欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Matlab —— 基础绘图

程序员文章站 2022-07-12 20:31:14
...

基础绘图

  • 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))

Matlab —— 基础绘图

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

Matlab —— 基础绘图

由此可见,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

Matlab —— 基础绘图

Plot Style

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

常用:

Data marekers Line types Colors
Cross(×) X Solid line ’ — ‘ Black k
Circle(○) O Dashed line ‘- - ‘ Blue b
Plus sign(+) + Dash-dotted line ‘-.’ Cyan c
Dot(.) . Dotted line ’ : ‘ Green g
Asterisk(*) * Magenta m
Red r
White w
Yellow y

- 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

Matlab —— 基础绘图

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^-')

Matlab —— 基础绘图

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');

Matlab —— 基础绘图

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}');

Matlab —— 基础绘图

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]);

Matlab —— 基础绘图
前后要有 $$.

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

\int 积分号

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

x^2sin(x) 被积函数

02x2sin(x)dx
去掉反斜 ‘\’
02x2sin(x)dx

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.2StartFiguresEditFigure Editmore propertiesEnd

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

Function Purpose
gca return the handle of the “current” axes
gcf return the handle of the “current” figure
allchild Find all children of specified objects
ancestor Find ancestor of graphics object
delete Detele an object
findall Find 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]);

Matlab —— 基础绘图
Alternative

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

Setting Font and Tick of Axes

set(gca,'FontSize', 25);

Matlab —— 基础绘图

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

Matlab —— 基础绘图

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

Matlab —— 基础绘图

Line Specification

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

Matlab —— 基础绘图

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]);

Matlab —— 基础绘图

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);

Matlab —— 基础绘图Figure 1
Matlab —— 基础绘图Figure 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 个

1 2 3
4 5 6
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

Matlab —— 基础绘图

Control of Grid, Box and Axis

Function Description
girs on/off Make the grid visible or invisible
box on/off Make the box visible or invisible
axis on/off Make the axes visible or invisible
axis normal Automatically adjust the aspect ratio of axes and the relative scaling of the data units
axis squal Make the aspect ratio so that the data units are the same in every direction
axis equal tight Set the axis limits to the range of data
axis image Let the plot box fits tightly around the data
axis ij Place the origin of the coordinate system in the upper left corner
axis xy Place the origin in the lower left corner

Saving Figures into Files

saveas(gcf, '<filename>','<formattype>');
Option Bitmap 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)
Option Vector 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