Matplotlib - Plot Line Color


Matplotlib – Plot Line Color Tutorial

In this tutorial, we’ll create a simple plot with a colored line using Matplotlib in Python.

Matplotlib - Plot Line Color

1. Import Matplotlib.pyplot

Import the Matplotlib library, specifically the pyplot module.

import matplotlib.pyplot as plt

2. Create Data

Define the data points for the X and Y axes.

x = [1, 2, 3, 4, 5]
y = [20, 30, 55, 70, 60]

In this case, x represents the values on the X-axis, and y represents the corresponding values on the Y-axis.

3. Plot Line with Color

Use Matplotlib to plot a line with a specified color.

plt.plot(x, y, color='green', marker='o')

color: This parameter determines the color of the line in the plot.

Choose a color name (e.g., 'green') or a hexadecimal color code (e.g., '#FF5733').

4. Customize and show the plot

Customize the plot with labels and titles, and then show the plot in a figure.

plt.title('Line Color Plot Example')
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.show()

Complete program to plot Line with Color using Matplotlib

Using all the above steps, let us write the complete program to draw a line with a specified color using Matplotlib plot() function.

Python Program

import matplotlib.pyplot as plt

# Example data
x = [1, 2, 3, 4, 5]
y = [20, 30, 55, 70, 60]

# Plot line with color
plt.plot(x, y, color='green', marker='o')

# Customize plot
plt.title('Line Color Plot Example')
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')

# Show the plot
plt.show()

Output

Matplotlib - Plot Line Color example

Now, let us use a hex value #FF7700 for the line color.

Python Program

import matplotlib.pyplot as plt

# Example data
x = [1, 2, 3, 4, 5]
y = [20, 30, 55, 70, 60]

# Plot line with color
plt.plot(x, y, color='#FF7700', marker='o')

# Customize plot
plt.title('Line Color Plot Example')
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')

# Show the plot
plt.show()

Output

Matplotlib - Plot Line Color with Hex value

Summary

That concludes our tutorial on creating a plot with a line of a specified color using Matplotlib in Python!