在同一张图上绘制两个直方图(使用相同的y轴)和一条线图(使用不同的y轴) [英] plot two histograms (using the same y-axis) and a line plot (using a different y-axis) on the same figure

查看:407
本文介绍了在同一张图上绘制两个直方图(使用相同的y轴)和一条线图(使用不同的y轴)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在同一张图上绘制两个直方图(使用相同的y轴)和一条线图(使用不同的y轴)?我正在使用Matlab 2014b.我知道,但它似乎仅适用于条形图?

How can I plot two histograms (using the same y-axis) and a line plot (using a different y-axis) on the same figure? I am using Matlab 2014b. I am aware of this but it seems to only work for bar plots?

这是我的直方图代码:

A = [1 2 2 2 3 4 5 5 5 5 5 5 5 5 5 6 6 6 7 7];
B = [6 6 6 7 7 7 7 7 7 7 8 8 8 9 9 10 10];
hist(A,7);
hold on
hist(B,7);
h = findobj(gca,'Type','patch');
set(h(1),'FaceColor','b','EdgeColor','b','facealpha',0.2)
set(h(2),'FaceColor','r','EdgeColor','r','facealpha',0.2)
xlabel('Day','fontsize',14)
ylabel('Frequency','fontsize',14)
xlim([1 10])

现在说我有这些数据:

Day = [1 2 3 4 5 6 7 8 9 10];
Prevalence = [3 2 4 8 5 6 7 8 9 5];

我想使用右y轴绘制这些数据(plot(Day,Prevalence)).

I want to plot these data (plot(Day,Prevalence)) using the right y-axis.

谢谢.

推荐答案

我认为这种解决方法可以满足您的要求.

I think this workaround will do what you want.

基本上在与绘制直方图相同的位置处创建一个新轴,但是将其color属性设置为"none",将YAxisLocation设置在右侧.然后,您可以为新轴分配所需的属性.

Basically create a new axes at the same position than the one in which the histograms are plot, however set its color property to 'none' and the YAxisLocation to the right. You can then assign the new axes the properties you want.

代码:

clear
clc


%// ====================
%// Your code
    A = [1 2 2 2 3 4 5 5 5 5 5 5 5 5 5 6 6 6 7 7];
    B = [6 6 6 7 7 7 7 7 7 7 8 8 8 9 9 10 10];
    hist(A,7);
    hold on
    hist(B,7);
    h = findobj(gca,'Type','patch');
    set(h(1),'FaceColor','b','EdgeColor','b','facealpha',0.2)
    set(h(2),'FaceColor','r','EdgeColor','r','facealpha',0.2)
    xlabel('Day','fontsize',14)
    ylabel('Frequency','fontsize',14)
    xlim([1 10])
%// ====================
Day = [1 2 3 4 5 6 7 8 9 10];
Prevalence = [3 2 4 8 5 6 7 8 9 5];

%// Get the current axes position to place the new one.
AxesPos = get(gca,'Position');

hold on

hax2 = axes('Position',AxesPos);

%// Plot the data
plot(Day,Prevalence,'--k','LineWidth',4,'Parent',hax2)

%// Set properties of the axes.
set(hax2,'Color','none','YAxisLocation','right','XTick',[],'XTickLabel','','YLim',[0 15])
ylabel('Prevalence','FontSize',16)

%// Rotate the label to correct orientation
LabelPos = get(get(hax2,'YLabel'),'Position');
set(get(hax2,'YLabel'),'Position',[LabelPos(1)+.2 LabelPos(2) LabelPos(3)],'Rotation',-90)

输出:

请注意,这离完美还很远……例如,第一个轴的左边框不可见……可以通过调整新轴的位置来解决.希望它能为您完成工作!

Note that it's far from perfect ...for example the left border of the first axes is not visible...that could be fixed by playing around with the position of the new axes. Hopefully it does the job for you!

这篇关于在同一张图上绘制两个直方图(使用相同的y轴)和一条线图(使用不同的y轴)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆