如何在MATLAB中实现双Y轴并列柱状图?
MATLAB绘制双Y轴并列柱状子图问题
我需要在MATLAB中绘制带双Y轴的并列柱状子图,但现有两段代码均未达到预期效果:
第一段代码:实现双Y轴,但柱状图重叠
代码如下:
% Create figure figure1 = figure('NumberTitle','off','Name','Figure','Color',[1 1 1]); %bar plot e scatter 2011 subplot1=subplot(3,2,1,'Parent',figure1) x1 = (1:5)'; y1 = tweetsvsnewsS3.somma_1_2; y2 = tweetsvsnewsS3.tweets_1; yyaxis left p1 = bar(x1,y1, 'BarWidth', 0.25); p1(1).FaceColor = [0.56 0.10 0.74]; yyaxis right p12=bar(x1,y2,'BarWidth', 0.25) p12(1).FaceColor = [0.41 0.28 0.79]; box(subplot1,'on'); hold(subplot1,'off'); set(subplot1,'XGrid','on','XMinorGrid','on','XMinorTick','on','YGrid','on',... 'YMinorGrid','on','YMinorTick','on'); set(gca,'xtick',1:12,... 'xticklabel',{'Nov 24','Nov 25','Nov 26','Nov 27','Nov 28'}) ylabel('count'); title('Data','FontSize',12)
效果:两组柱状图上下重叠,无法区分数据。
第二段代码:实现并列柱状图,但无双Y轴
代码如下:
% Create figure figure1 = figure('NumberTitle','off','Name','Figure','Color',[1 1 1]); %bar plot e scatter 2011 subplot1=subplot(3,2,1,'Parent',figure1) x1 = (1:5)'; y1 = tweetsvsnewsS3.somma_1_2; y2 = tweetsvsnewsS3.tweets_1; p1 = bar(x1,[y1,y2],'BarWidth', 0.80); p1(1).FaceColor = [0.56 0.10 0.74]; p1(2).FaceColor = [0.41 0.28 0.79]; box(subplot1,'on'); hold(subplot1,'off'); set(subplot1,'XGrid','on','XMinorGrid','on','XMinorTick','on','YGrid','on',... 'YMinorGrid','on','YMinorTick','on'); set(gca,'xtick',1:12,... 'xticklabel',{'Nov 24','Nov 25','Nov 26','Nov 27','Nov 28'}) ylabel('count'); title('Data','FontSize',12)
效果:两组数据并列显示,但只有单Y轴,无法适配两组数据的数值范围。
解决方案
通过调整X轴偏移量实现并列,同时保留双Y轴功能:
% 创建画布 figure1 = figure('NumberTitle','off','Name','Figure','Color',[1 1 1]); subplot1 = subplot(3,2,1,'Parent',figure1); hold(subplot1,'on'); % 保持绘图状态 x1 = (1:5)'; y1 = tweetsvsnewsS3.somma_1_2; y2 = tweetsvsnewsS3.tweets_1; bar_width = 0.35; % 设置柱状图宽度 % 左Y轴柱状图:X轴位置左移 yyaxis left; p1 = bar(x1 - bar_width/2, y1, bar_width); p1.FaceColor = [0.56 0.10 0.74]; ylabel('左Y轴计数'); % 标注左Y轴含义 % 右Y轴柱状图:X轴位置右移 yyaxis right; p12 = bar(x1 + bar_width/2, y2, bar_width); p12.FaceColor = [0.41 0.28 0.79]; ylabel('右Y轴计数'); % 标注右Y轴含义 % 配置坐标轴样式 box(subplot1,'on'); set(subplot1,'XGrid','on','XMinorGrid','on','XMinorTick','on','YGrid','on',... 'YMinorGrid','on','YMinorTick','on'); set(subplot1,'xtick',1:5,... % 修正刻度数量,匹配数据点 'xticklabel',{'Nov 24','Nov 25','Nov 26','Nov 27','Nov 28'}); title('Data','FontSize',12); hold(subplot1,'off');
关键调整说明:
- 通过
x1 ± bar_width/2给两组柱状图设置X轴偏移,实现并列效果 - 开启
hold on确保双Y轴绘图不被覆盖 - 修正
xtick为1:5,避免刻度与标签数量不匹配的异常 - 分别给左右Y轴添加专属标签,明确数据对应关系
内容的提问来源于stack exchange,提问作者Rachele Franceschini
相关产品推荐
相关产品推荐

