Main Content

叠加条形图

此示例演示如何叠加两个条形图并指定条形的颜色和宽度。然后演示如何添加图例、显示网格线和指定刻度标签。

创建一个条形图。将条形宽度设置为 0.5,使条形使用 50% 的可用空间。通过将 FaceColor 属性设置为一个 RGB 颜色值来指定条形的颜色。

x = [1 2 3 4 5];
temp_high = [37 39 46 56 67]; 
w1 = 0.5; 
bar(x,temp_high,w1,'FaceColor',[0.2 0.2 0.5])

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

在第一个条形图上绘制第二个条形图。使用 hold 函数保留第一个图形。将条形宽度设置为 .25,使条形使用 25% 的可用空间。为该条形颜色指定一个不同的 RGB 颜色值。

temp_low = [22 24 32 41 50];
w2 = .25;
hold on
bar(x,temp_low,w2,'FaceColor',[0 0.7 0.7])
hold off

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

添加网格线、y 轴标签,并在左上角添加图例。按照创建图表的顺序指定图例说明。

grid on
ylabel('Temperature (\circF)')
legend({'Average High','Average Low'},'Location','northwest')

Figure contains an axes object. The axes object with ylabel Temperature ( degree F) contains 2 objects of type bar. These objects represent Average High, Average Low.

通过设置坐标区对象的 XTickXTickLabel 属性,指定 x 轴刻度标签。XTick 属性用于指定沿 x 轴的刻度值位置。XTickLabel 属性用于指定每个刻度值要使用的文本。使用 XTickLabelRotation 属性旋转标签。使用圆点表示法设置属性。

ax = gca;
ax.XTick = [1 2 3 4 5]; 
ax.XTickLabels = {'January','February','March','April','May'};
ax.XTickLabelRotation = 45;

Figure contains an axes object. The axes object with ylabel Temperature ( degree F) contains 2 objects of type bar. These objects represent Average High, Average Low.

另请参阅

| |