Matlab 二维笛卡尔坐标系

Matlab绘制二维笛卡尔坐标系

这是一个经常会用到的程序,根据散点数据画出折线图,希望对你有所帮助。

clc;clear;close all;
%% 绘制坐标系
% 新建图窗
fig=figure(1);
% 确定横轴范围
x=-10:11;
%确定纵轴范围
y=-10:11;
%保持图窗,继续绘图
hold on;
%画横纵轴
plot([0 0],[min(y)-1 max(y)+1],'k','LineWidth',1);
plot([min(x)-1 max(x)+1],[0 0],'k','LineWidth',1);
% 画箭头
ax=[max(x)+1,max(x),max(x);0,0.2,-0.2];
fill(ax(1,:),ax(2,:),'k');
ay=[0, 0.2,-0.2;max(y)+1,max(y),max(y)   ];
fill(ay(1,:),ay(2,:),'k');
% 标记O,x,y
text(-0.3,-0.4,'O','FontName','consolas','FontAngle','Italic','FontSize',10,'FontWeight','bold','LineWidth',10,'HorizontalAlignment','center');
text(max(x)+0.2, -0.5, 'x','FontName','consolas','FontAngle','Italic','FontSize',10, 'FontWeight','bold','LineWidth',10,'VerticalAlignment','middle');
text(0.5, max(y)+0.5, 'y', 'FontName','consolas','FontAngle','Italic','FontSize',10, 'FontWeight','bold','LineWidth',10,'HorizontalAlignment','center');
%
% 坐标轴刻度
for i=1:length(x)-1
    if x(i)~=0
        plot([x(i),x(i)],[0,0.2],'k'); hold on
        a=text(x(i),-0.4,num2str(x(i)));
        set(a,'HorizontalAlignment','center')
        set(a,'FontName','consolas','FontSize',6,'FontWeight','bold','LineWidth',10);
    end
end
for i=1:length(y)-1
    if y(i)~=0
        plot([0,0.15],[y(i),y(i)],'k'); hold on
        b=text(-0.6,y(i),num2str(y(i)));
        set(b,'HorizontalAlignment','center')
        set(b,'FontName','consolas','FontSize',6,'FontWeight','bold','LineWidth',10);
    end
end
%关闭原有坐标系
axis off;
%使x轴和y轴的单位长度相同
axis equal;
hold on;
%%  绘制理论曲线
x=-10:0.001:10;
y=2.*x+3+4*sin(0.5.*pi.*x);
k=find((-12<y)&(y<10));
plot(x(k),y(k),'r-');
hold on
%%  绘制散点图
x=-10:1:10;
y=2.*x+3+4*sin(0.5.*pi.*x)+randn(size(x));
k=find((-12<y)&(y<10));
plot(x(k),y(k),'k.');
hold on
%% 根据散点做出折线图
plot(x(k),y(k),'b-');
%% 保存
saveas(fig,'scatter.jpg');

结果如图:
Matlab 二维笛卡尔坐标系_第1张图片

你可能感兴趣的:(MATLAB)