初始代码:
% 创建横坐标的数据点
x = linspace(0, 12, 1000);
% 计算纵坐标的数据点
y = cos(x);
% 绘制曲线
plot(x, y, 'r');
% 设置坐标轴范围
xlim([0, 12]);
ylim([-1, 1]);
% 给y坐标着色
set(gca, 'YColor', 'g');
% 绘制注释点
hold on;
x_annotation = 7;
y_annotation = cos(x_annotation);
plot(x_annotation, y_annotation, 'r*', 'MarkerSize', 10);
% 绘制箭头指向cos(4)的值并添加注释
x_arrow = 4;
y_arrow = cos(x_arrow);
plot(x_arrow, y_arrow, 'ro', 'MarkerSize', 8, 'MarkerFaceColor', 'r');
text(x_arrow, y_arrow, sprintf('cos(4) = %.4f', y_arrow), 'VerticalAlignment', 'bottom');
% 添加标题和轴标签
title('y = cos(x)');
xlabel('x');
ylabel('y');
% 显示图例
legend('y = cos(x)', 'Annotation Point', 'cos(4)', 'Location', 'northwest');
画出的图例为:
存在问题:
1.星号点的注释没有显示
2.y坐标是绿色的,没有y=0的绿色直线
3.cos(x)=4的注释点是圆圈
4.背景不是网格
解决1:
添上代码注释:对应的xy,一开始忘了添加%d
text(x_annotation, y_annotation, sprintf('x = %d ,y = %.4f',x_annotation,y_annotation), 'VerticalAlignment', 'bottom');
解决2:
添加一条y=0绿色直线
yline(0,'g')
参考链接:具有y值常量的水平线(yline函数
解决3:
注释点向左指箭头
参考链接:plot函数用法
修改代码:
将plot函数里面的参数改变
plot(x_arrow, y_arrow, '<-', 'MarkerSize', 8, 'MarkerFaceColor', 'r');
解决4:
添加网格线的背景
grid on
参考链接:添加网格线并编辑位置
完整代码:
% 创建横坐标的数据点
x = linspace(0, 12, 1000);
% 计算纵坐标的数据点
y = cos(x);
% 绘制曲线
plot(x, y, 'r');
% 设置坐标轴范围
xlim([0, 12]);
ylim([-1, 1]);
% 给y坐标着色
%set(gca, 'YColor', 'g');
% 绘制注释点
hold on;
x_annotation = 7;
y_annotation = cos(x_annotation);
plot(x_annotation, y_annotation, 'r*', 'MarkerSize', 10);
text(x_annotation, y_annotation, sprintf('x = %d ,y = %.4f',x_annotation,y_annotation), 'VerticalAlignment', 'bottom');
% 绘制箭头指向cos(4)的值并添加注释
x_arrow = 4;
y_arrow = cos(x_arrow);
plot(x_arrow, y_arrow, '<-', 'MarkerSize', 8, 'MarkerFaceColor', 'r');
text(x_arrow, y_arrow, sprintf('cos(4) = %.5f', y_arrow), 'VerticalAlignment', 'bottom');
% 添加标题和轴标签
title('余弦曲线y = cos(x)');
xlabel('0≤x≤4Π');
ylabel('y = cos(x)');
%添加网格线
grid on
%添加一条绿色的直线
yline(0,'g')
% 显示图例
%legend('y = cos(x)', 'Annotation Point', 'cos(4)', 'Location', 'northwest');
最后结果:
还有其他一些参考代码:
另一种写法也能得到:
x = linspace(0,4*pi,1000);
y1=cos(x);
hold on
title('余弦曲线y=cos(x)')
plot(x,y1,'r-')
yline(0, 'g-.')
axis([0 13 -1 1])
xlabel('0≤x≤4π')
ylabel('y=cos(x)')
txt = ['\leftarrow cos(4) = ',num2str(cos(4))];
text(4,cos(4),txt)
plot(7,cos(7),'b*');
txt = [' x = 7, y = ',num2str(cos(7))];
text(7,cos(7),txt)
#其他版本
x=0:0.05:4*pi;
y=cos(x);
plot(x,y,'r');
box off;
grid on;
xlim([0 4*pi]);
hline=refline(0,0);
hline.Color='g';
hline.LineStyle='-.';
title('余弦曲线y=cos(x)');
xlabel('0 \leq x \leq 4\pi');
ylabel('y=cos(x)');
text(4,cos(4),['\leftarrow cos(4)=',num2str(cos(4))]);
hold on;
plot(7,cos(7),'*b');
text(7,cos(7),[' x=7,y=',num2str(cos(7))]);
以上都有异曲同工之处,都能得到上面的图。