Main Content

创建包含双 y 轴的图。

以下示例演示如何使用 yyaxis 函数创建左侧和右侧带有 y 轴的图表。此外,它还演示如何标记每个轴、合并多个绘图以及清除与两侧或其中一侧关联的绘图。

绘制数据对左侧 y 轴的图。

创建左右两侧都有 y 轴的坐标区。yyaxis left 命令用于创建坐标区并激活左侧。后续图形函数(例如 plot)的目标为活动侧。绘制数据对左侧 y 轴的图。

x = linspace(0,25);
y = sin(x/2);
yyaxis left
plot(x,y);

Figure contains an axes object. The axes object contains an object of type line.

绘制数据对右侧 y 轴的图。

使用 yyaxis right 激活右侧。然后,绘制一组数据对右侧 y 轴的图。

r = x.^2/2;
yyaxis right
plot(x,r);

Figure contains an axes object. The axes object contains 2 objects of type line.

添加标题和轴标签

使用 yyaxis leftyyaxis right 命令控制坐标区的哪一侧为活动侧。然后添加标题和轴标签。

yyaxis left
title('Plots with Different y-Scales')
xlabel('Values from 0 to 25')
ylabel('Left Side')

yyaxis right
ylabel('Right Side')

Figure contains an axes object. The axes object with title Plots with Different y-Scales, xlabel Values from 0 to 25, ylabel Right Side contains 2 objects of type line.

基于每一侧绘制其他数据图

使用 hold on 命令再向左侧添加两个线条。向右侧添加一个误差条。新图与对应的 y 轴使用相同的颜色,并循环使用线型序列。hold on 命令同时影响左右两侧。

hold on

yyaxis left
y2 = sin(x/3);
plot(x,y2);
y3 = sin(x/4);
plot(x,y3);

yyaxis right
load count.dat;
m = mean(count,2);
e = std(count,1,2);
errorbar(m,e)

hold off

Figure contains an axes object. The axes object with title Plots with Different y-Scales, xlabel Values from 0 to 25, ylabel Right Side contains 5 objects of type line, errorbar.

清除坐标区的一侧

首先激活右侧 y 轴,然后使用 cla 命令清除右侧 y 轴的数据。

yyaxis right
cla

Figure contains an axes object. The axes object with title Plots with Different y-Scales, xlabel Values from 0 to 25, ylabel Right Side contains 3 objects of type line.

清除坐标区并删除右侧 y

使用 cla reset 清除整个坐标区数据并删除右侧的 y 轴。

cla reset

Figure contains an axes object. The axes object is empty.

现在,当您创建绘图时,绘图将仅包含一个 y 轴。例如,基于单个 y 轴绘制三条线条。

xx = linspace(0,25);
yy1 = sin(xx/4); 
yy2 = sin(xx/5); 
yy3 = sin(xx/6);
plot(xx,yy1,xx,yy2,xx,yy3)

Figure contains an axes object. The axes object contains 3 objects of type line.

将第二个 y 轴添加到现有图形

使用 yyaxis 向现有图表添加第二个 y 轴。现有绘图和左侧的 y 轴不会更改颜色。右侧 y 轴将使用坐标区色序中的下一种颜色。添加到坐标区中的新绘图使用与对应的 y 轴相同的颜色。

yyaxis right
rr1 = exp(xx/6);
rr2 = exp(xx/8);
plot(xx,rr1,xx,rr2)

Figure contains an axes object. The axes object contains 5 objects of type line.

另请参阅

函数

相关主题