Change the line opacity in Matplotlib
Changing Line Opacity in Matplotlib means adjusting the transparency level of a line in a plot. Opacity controls how much the background or overlapping elements are visible through the line. A fully opaque line is solid, while a more transparent line allows other elements behind it to be seen. Let's explore different methods to achieve this.
Using alpha parameter
alpha parameter in Matplotlib controls the transparency level of a plot. It accepts values between 0 (completely transparent) and 1 (fully opaque). By setting alpha to a value less than 1, you can make the line appear more faded, which is useful for overlapping lines or improving visualization clarity.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create plot with transparency
plt.plot(x, y, color='blue', linewidth=2, alpha=0.5, label='Alpha = 0.5')
plt.legend()
plt.show()
Output:


Explanation: plt.plot(x, y, color='blue', linewidth=2, alpha=0.5) plots the sine wave with a blue color, line width of 2 and alpha=0.5 (50% transparency).
Using RGBA Color format
Matplotlib also allows defining colors in the RGBA format, where the first three values represent the red, green, and blue components (RGB), and the fourth value specifies the opacity (A) or alpha channel. This method provides more flexibility in defining colors while setting transparency in the same step.
import matplotlib.pyplot as plt
plt.plot(x, y, color=(0, 0, 1, 0.4), linewidth=2, label='RGBA (0,0,1,0.4)')
plt.legend()
plt.show()
Output:


Explanation: color=(0, 0, 1, 0.4) specifies the color in the (Red, Green, Blue, Alpha) format. (0,0,1) represents blue and 0.4 sets the transparency to 40%.
Adjusting opacity in a loop for multiple lines
When plotting multiple lines in the same figure, you can assign different transparency levels to each line using a loop. By iterating over a list of colors and corresponding alpha values, you can create a visually appealing chart where each line has a unique transparency level.
import matplotlib.pyplot as plt
a = ['red', 'green', 'blue', 'purple'] # colors
b = [0.1, 0.3, 0.5, 0.8] # alphas
plt.figure()
for i in range(4):
plt.plot(x, np.sin(x + i), color=a[i], linewidth=2, alpha=b[i], label=f'Alpha = {b[i]}')
plt.legend()
plt.show()
Output:

Explanation: for loop iterates through these lists, plotting four sine waves with different colors and transparency settings. The plt.plot function is used to plot each sine wave, where np.sin(x + i) shifts the waves to avoid overlap, and the alpha parameter controls the transparency of each line.