0
0
MatlabHow-ToBeginner ยท 3 min read

How to Change Line Color in MATLAB Plots

In MATLAB, you can change the line color of a plot by specifying the 'Color' property when calling the plot function or by setting it on the line object after plotting. Use color names like 'r' for red or RGB triplets like [0 0.5 0] for custom colors.
๐Ÿ“

Syntax

The basic syntax to change line color in MATLAB is:

  • plot(x, y, 'Color', colorValue) - sets the line color during plotting.
  • h = plot(x, y); then h.Color = colorValue; - changes color after plotting.

Here, colorValue can be a short color name like 'r' (red), a long name like 'blue', or an RGB triplet like [1 0 0].

matlab
plot(x, y, 'Color', colorValue)
h = plot(x, y);
h.Color = colorValue;
๐Ÿ’ป

Example

This example shows how to plot a sine wave with a green line using the 'Color' property and then change it to magenta after plotting.

matlab
x = linspace(0, 2*pi, 100);
y = sin(x);

% Plot with green line
h = plot(x, y, 'Color', 'g');
title('Sine Wave with Green Line');

pause(2); % Pause to see first plot

% Change line color to magenta
h.Color = [1 0 1]; % RGB for magenta

title('Sine Wave with Magenta Line');
Output
A plot window showing a sine wave first in green, then after 2 seconds, the line color changes to magenta.
โš ๏ธ

Common Pitfalls

Common mistakes when changing line color in MATLAB include:

  • Using color names without quotes, which causes errors.
  • Trying to set color before creating the plot object.
  • Using invalid RGB values outside the range 0 to 1.

Always use quotes for color names and valid RGB triplets.

matlab
% Wrong: missing quotes around color name
% plot(x, y, 'Color', r) % causes error

% Correct:
plot(x, y, 'Color', 'r')

% Wrong: RGB values out of range
% plot(x, y, 'Color', [1.5 0 0]) % invalid

% Correct:
plot(x, y, 'Color', [1 0 0])
๐Ÿ“Š

Quick Reference

Color SpecificationExampleDescription
Short name'r'Red line
Long name'blue'Blue line
RGB triplet[0 0.5 0]Dark green line
Hex code (newer MATLAB)'#FF00FF'Magenta line
โœ…

Key Takeaways

Use the 'Color' property in the plot function to set line color directly.
Color values can be short names, long names, RGB triplets, or hex codes.
Always enclose color names in quotes to avoid errors.
You can change line color after plotting by modifying the line object's Color property.
RGB values must be between 0 and 1 for valid colors.