matlabplotaxisscatter-plothorizontal-line

Plotting Additional Line w/o adjusting Plot Window around Original Data in Matlab


I have a scatterplot of data in Matlab, along with a horizontal linegraph which divides two sub groups of this data - all on the same plot. I have plotted these two entities separately using the hold on command.

Ideally, I want the plot window to automatically adjust to just the scatterplot data, and would prefer the horizontal line I plotted to simply extend off the screen in all cases. Is there a simple way to do this?

At the moment when I change the limits of the horizontal line, the graph window shifts to accommodate these points, skewing the view of the scatterplot data I'm actually interested in.

Example:

% central line segment
boundary_line = plot(csv_results.data(:,9),csv_results.data(:,10));

% negative extension of line segment off screen
line_negext = plot([-10,csv_results.data(1,9)],[csv_results.data(1,10),csv_results.data(1,10)]);

% positive extension of line segment off screen
line_posext = plot([10,csv_results.data(6,9)],[csv_results.data(6,10),csv_results.data(6,10)]);

% scatterplot data of interest
scatt_data = plot(csv_results.data(:,3),csv_results.data(:,4));

UPDATE: My problem is that, as seen in my code above, I need to plot two line segments at different y values that continue to positive and negative infinity, which link up to an existing plot in the middle. If I use yline I can simply draw one horizontal line - if I use xlim I risk cropping out data for subsequent runs..


Solution

  • Image showing horizontal line

    If you want to adjust the axis to more restrictive portion (reduce), then xlim() and ylim() get the job done. Horizontal lines drawn by yline() will persist, as will vertical lines drawn by xline(). Note that xline() and yline() should work for releases including R2018b and later.

    % MATLAB R2019a
    % Sample Data
    n = 10;
    X1 = 5*rand(n,1);
    Y1 = 5*rand(n,1);
    X2 = 5 + 5*rand(n,1);
    Y2 = 5 + 5*rand(n,1);
    
    figure, hold on
    yline(5) 
    scatter(X1,Y1,'bo')
    scatter(X2,Y2,'rd')
    scatter(X1,Y2,'ks')
    xlim([0 5])
    

    Notice that by calling xlim() for a larger x-axis range also expands the horizontal line.

    xlim([-1,12])
    

    If you plot new data after xlim() outside the range, the plot won't automatically adjust. However, if you do so before calling xlim(), then the horizontal line will expand. Try the example below.

    figure, hold on
    yline(5) 
    scatter(X1,Y1,'bo')
    scatter(X2,Y2,'rd')
    scatter(X1,Y2,'ks')
    

    Then immediately execute

    scatter(100*rand(n,1),Y1)
    

    and see that the horizontal line has expanded to cover the new, much longer x-axis. Image showing expanded horizontal line


    After posting this answer, I found: How to draw horizontal and vertical lines in MATLAB?