1. 程式人生 > >matlib畫圖基本用法(1)

matlib畫圖基本用法(1)

MATLAB基本繪圖用法

1.plot的基本用法

# 繪製基本畫素點(x, y)的座標
plot(x, y);
# 如果只給定y的座標,那麼x軸將會按x=[1,2,3,...]分佈
plot(y);
# 將兩個影象畫在一張圖上
hold on
plot(cos(0:pi/20:pi));
plot(sin(0:pi/20:pi));
hold off
# 畫出不同風格的線段
plot(cos(0:pi/20:pi), 'or--');
plot(sin(0:pi/20:pi), 'xg');

2.legend() 圖例

legend('cos(x)', 'sin(x)');

3.加標題,座標軸

# 為圖加標題
title('Functioin Plots');
# 為圖加x軸
xlabel('t = 0 to 2/pi');
# 為圖加y軸
ylabel('values of sin(t) and e^{-x}')

4.在圖上寫文字和畫箭頭

# 在圖上書寫文字
text()
# 在圖上畫一個箭頭
annotation()
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) ds $$';
text(0.25,2.5,str,'Interpreter','latex');
annotation('arrow', 'X',[0.32,0.5], 'Y',[0.6,0.4]);

5.修改圖形的引數

# 獲取影象的引數
x = linspace(0, 2*pi, 1000);
y = sin(x);
plot(x,y);
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.0060
         XDataMode: 'manual'
       XDataSource: ''
       YDataSource: ''
       ZDataSource: ''
# 獲取座標系的屬性
get(gca);

修改座標系的引數

# 修改座標系X軸和Y軸的引數
set(gca, 'XLim', [0, 2*pi]);
set(gca, 'YLim', [-1.2, 1.2]);
# 或者
xlim([0, 2*pi]);
ylim([-1.2, 1.2])

# 修改座標系字型的大小
set(gca, 'FontSize', 25)

# 修改座標系引數之間的間隔
set(gca, 'XTick', 0:pi/2:2*pi);
set(gca, 'XTickLabel', 0:90:360);
# 將X軸引數用π來表示
set(gca, 'FontName', 'symbol');
set(gca, 'XTickLabel', {'0', 'p/2', 'p', '3p/2', '2p'})

修改線條的引數

# 設定線條的風格和寬度
 set(h, 'LineStyle', '-', 'LineWidth', 7.0, 'Color', 'g');
# 設定座標的風格
plot(x, '-md', 'LineWidth', 2, 'MarkerEdgeColor', 'k', ...
'MarkerFaceColor', 'g', 'MarkerSize', 10);

畫多個圖(gca和gcf只能指到圖二)

x = -10:0.1:10;
y1  = x.^2 - 8;
y2 = exp(x);
figure, plot(x, y1);
figure, plot(x, y2);

圖的大小和位置

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

在一個圖上畫很多圖

# 其中m指的是行,n指的是列, 1代表的是第一個小圖
subplot(m, n, 1)

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 # X軸和Y軸的長度相同
subplot(2, 2, 3); plot(x, y); axis equal  # X軸和Y軸的比例相同
subplot(2, 2, 4); plot(x ,y); axis equal tight # X軸和Y軸要與影象相切

對座標系的一些操作

# 關閉座標軸
axis off
# 開啟座標軸
axis on
# 關閉座標軸上面和右邊的線
box off
# 開啟座標軸上面和右邊的線
box on
# 關閉單元格
grid off
# 開啟單元格
grid on

6.將圖片儲存到檔案中

saveas(gcf, '<filename>', '<formatype>');