Search code examples
matlabchartsohlcv

Create a OHLC-Volume chart in Matlab


I want to create a stock chart in Matlab-R2018a that contains both data and volume in the same figure with the Y-axis showing two different scales as below. The placement of the x-axis labels is not important.

example: enter image description here

I tried subplot but can't get the final figure to look like the image. Maybe tiledlayout might do it but it's not available in R2018a. This solution Plot multiple similar data in same graph comes closest to what I want but the Data Cursor gives the wrong values.

x = 470:0.1:484;
z1 = cos(x)/2;
z2 = sin(x)/3;
z3 = cos(x+0.2)/2.3;
figure
plot(x,z1);
hold on
plot(x,z2+2);
plot(x,z3+4);
ytick = [-0.5,0.0,0.5];
set(gca,'ytick',[ytick,ytick+2,ytick+4]);
set(gca,'yticklabel',[ytick,ytick,ytick]);
text(484.5,0,'z1')
text(484.5,2,'z2')
text(484.5,4,'z3')`

Any ideas how to modify it to get the correct values? Or maybe an alternative solution? 
Any help would be appreciated. Thanks 

Solution

  • If you just need to plot two datasets, you can use yyaxis, and then just play with the ylim of your two axis to have the plots stacked and the right datatips values:

    x = 470:0.1:484;
    z1 = cos(x)/2;
    z2 = sin(x)/3;
    
    figure
    yyaxis left
    plot(x,z1);
    yticks([-0.5 0 0.5])
    ylim([-2.5 0.5])
    
    hold on
    yyaxis right
    plot(x,z2);
    ylim([-0.5 2.5])
    yticks([-0.5 0 0.5])
    

    enter image description here


    Now if you want all the ticks to be on the left side you have to manually set the position and labels of the ticks on the left axis, so that their position coincides with the position they would have on the right axis. You also have to remove the ticks on the right axis.

    In other words:

    x = 470:0.1:484;
    z1 = cos(x)/2;
    z2 = sin(x)/3;
    
    figure
    yyaxis left
    plot(x,z1);
    ylims_left = [-2.5 0.5];
    ylim(ylims_left);
    
    hold on
    yyaxis right
    plot(x,z2);
    ylims_right = [-0.5 2.5];
    ylim(ylims_right);
    % remove right axis ticks
    yticks([]);
    set(gca,'YColor','k');
    
    yyaxis left
    ticks_left = [-0.5 0 0.5];
    ticks_right = [-0.5 0 0.5];
    % Tick positions on the right axis relative to the lower limits
    tickPos = (ticks_right - ylims_right(1))/(ylims_right(2) - ylims_right(1));
    % Equivalent relative position on the left axis, relative to the lower limit
    tickPos_Eq = ylims_left(1) + tickPos*(ylims_left(2) - ylims_left(1));
    yticks([tickPos_Eq ticks_left])
    set(gca,'YTickLabel',[ticks_right ticks_left]);
    set(gca,'YColor','k');
    

    enter image description here