Search code examples
matlabplotmatlab-figurelogarithm

Logarithmic x axis in a stackplot MatLab


I'm trying to make a stack plot from a table, to present several variables with the same x-axis. however, I want the x-axis to be logarithmic. I couldn't find any way in stackplot documentation. Does anyone have any suggestions on how I can solve this?

I have tried using subplots instead, however, that way my graphs would not fit all on one page and I would have a lot of white space between the subplots. Therefore, I chose stackplot to make it more nice and less space-consuming.

tbl = readtable('usage.csv'); 

newYlabels = {'Heating (kWh/year)','Cooling (kWh/year)','Electricity (kWh/year)'};  
stackedplot(tbl,[{2:16},{17:27},{28:35}],'XVariable',[1],'DisplayLabels',newYlabels);

Here is the output of the code:

text

Here is an image of what I'm trying to make, but the x-axis needs to be the real variable (\beta) in logarithmic scale

text


Solution

  • stackedplot has unfortunately no logarithmic axes option, and since it creates a StackedAxes instead of a normal Axes object, there is no way to changes this.

    If the only reason you want to use stackedplot is to have less white-space, you might want to check out tight_subplot on the Matlab FEX. This would allow you to just do: set(ax, 'XScale', 'log').

    You can however take the log of your x-data, and add that to the table:

    tbl = readtable('outages.csv');     % sample data
    tbl = sortrows(tbl, 'OutageTime');  % sort by date
    
    % make x vector; for example just row numbers
    x = (1:size(tbl,1)).';
    xlog = log10(x);
    
    % add x to table
    tbl.Xlog = xlog; 
    tbl.X = x;
    
    % plot normal x
    f = figure(1); clf;
    s = stackedplot(tbl, {'Loss'}, 'XVariable', 'X');
    xlabel('rows');
    
    % plot log(x)
    f = figure(2); clf;
    s = stackedplot(tbl, {'Loss'}, 'XVariable', 'Xlog');
    xlabel('log(rows)')
    

    Normal: enter image description here

    Log: enter image description here