1

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?

This is my histogram 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])

Now say I have these data:

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

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

Thanks.

user2861089
  • 1,205
  • 4
  • 22
  • 44

1 Answers1

3

I think this workaround will do what you want.

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.

Code:

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)

Output:

enter image description here

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!

Benoit_11
  • 13,905
  • 2
  • 24
  • 35