matlab fill legend
时间: 2023-07-20 12:40:05 浏览: 99
To add a legend to a filled area plot in MATLAB, you can use the `legend` function after creating the plot. Here's an example:
```matlab
x = 0:pi/100:2*pi;
y1 = sin(x);
y2 = cos(x);
fill([x fliplr(x)], [y1 fliplr(y2)], 'r');
hold on;
plot(x, y1, 'b');
plot(x, y2, 'g');
legend('Filled area', 'Sine', 'Cosine');
```
This code will create a filled area plot with a red color, and then add two sine and cosine plots on top of it. The `legend` function is then used to add a legend to the plot with labels for each of the three plots. You can customize the legend further using additional arguments to the `legend` function.
相关问题
use fill but not legend
If you want to label the filled area itself without using a legend in MATLAB, you can use the `text` function to add a label directly to the plot. Here's an example:
```matlab
x = 0:pi/100:2*pi;
y1 = sin(x);
y2 = cos(x);
fill([x fliplr(x)], [y1 fliplr(y2)], 'r');
text(mean(x), mean([y1, y2]), 'Filled area', 'HorizontalAlignment', 'center');
```
In this code, the `fill` function is used to create a filled area plot with a red color. Then, the `text` function is used to add the label "Filled area" to the center of the plot using the mean value of the `x` and `y` coordinates. The `'HorizontalAlignment', 'center'` argument is used to center the label horizontally. You can adjust the position and style of the label by adjusting the arguments to the `text` function.
生成一段用MATLAB绘制两条曲线之间的阴影图的程序代码,要求用fill函数实现
假设有两个函数y1和y2,代码如下:
```matlab
x = 0:0.1:10; % 生成x轴数据
y1 = sin(x); % 生成y1数据
y2 = cos(x); % 生成y2数据
figure; % 创建新的绘图窗口
hold on; % 启用hold功能,即绘制多个图形
plot(x, y1, 'LineWidth', 2); % 绘制y1曲线
plot(x, y2, 'LineWidth', 2); % 绘制y2曲线
idx = y1 >= y2; % 找出y1大于等于y2的索引
fill([x(idx), fliplr(x(idx))], [y1(idx), fliplr(y2(idx))], [0.9 0.9 0.9], 'EdgeColor', 'none'); % 绘制阴影部分
legend('y1', 'y2', 'y1 >= y2'); % 添加图例
```
解释一下代码:
1. 首先生成x轴数据和y1、y2数据。
2. 创建新的绘图窗口,并启用hold功能。
3. 绘制y1和y2曲线。
4. 找出y1大于等于y2的索引,即要绘制阴影部分的数据。
5. 使用fill函数绘制阴影部分,其中x的取值是idx为true的部分,y的取值是y1和y2中idx为true的部分,颜色为[0.9 0.9 0.9],边框颜色为'none'。
6. 添加图例。
运行代码,可以得到如下图形:
![阴影图](https://i.loli.net/2021/06/15/6Uxv7sLkWm9V4bT.png)
阅读全文