How to place a colored rectangle in background of part of a figure which has a logarithmic axis

20 views (last 30 days)
I am trying to place a gray rectangle in the background of part of a figure. The figure has a logarithmic y-axis. I can place the rectangle just fine as long as I do not try to scale the axis. When I do that, I get the error message
Warning: Error updating Rectangle.
DataSpace or ColorSpace transform method failed.
Any suggestions? I have tried including the rectangle code before and after the rest of the commands for the figure.

Answers (1)

Jaswanth
Jaswanth on 2 Aug 2024
Hi,
To place a coloured rectangle in the background of a figure with a logarithmic y-axis in MATLAB, you can use the fill function instead of the rectangle function.
Please refer to the following example code demonstrating the implementation discussed above:
% Sample data
x = linspace(1, 10, 100);
y = exp(x);
% Create figure
figure;
hold on;
% Plot data with logarithmic y-axis
plot(x, y);
set(gca, 'YScale', 'log');
% Define the coordinates for the rectangle
x_rect = [2, 8, 8, 2];
y_rect = [1e2, 1e2, 1e4, 1e4];
% Plot the rectangle using fill
fill(x_rect, y_rect, [0.8 0.8 0.8], 'EdgeColor', 'none');
% Bring the plot to the front
uistack(plot(x, y), 'top');
In the above example, x_rect and y_rect define the vertices of the rectangle.
The fill function is used to draw the rectangle, and the color ‘[0.8 0.8 0.8]’ corresponds to gray. The uistack function ensures that the plot remains on top of the rectangle.
Kindly refer to following MathWorks documentation to know more about the functions discussed above discussed above:
I hope the solution provided above is helpful.

Categories

Find more on Specifying Target for Graphics Output in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!