Colors and Transparency
Colors
When bar charts were discussed, the colors of individual bars were customized. To change the color for all plots uniformly, use the color
keyword argument.
import matplotlib.pyplot as plt import numpy as np data_linear = np.arange(0, 11) data_squared = data_linear ** 2 data_log = np.exp(data_linear) # Setting the color of the first line plot plt.plot(data_linear, label='linear function', color='red') # Setting the color of the second line plot plt.plot(data_squared, '-o', label='quadratic function', color='blue') plt.xticks(data_linear) plt.xlabel('x', loc='right') plt.ylabel('y', loc='top', rotation=0) plt.legend() plt.show()
In this case, the red
color was set for the first line plot, and the second one was set to blue
. Unlike scatter or bar plots, which consist of multiple elements, a line plot represents a single element, so only one color can be assigned to it. For comparison, consider the following bar chart example from an earlier section:
import matplotlib.pyplot as plt programming_languages = ['Python', 'Java', 'C#', 'C++'] shares = [40, 30, 17, 13] # Setting a separate color for each bar plt.bar(programming_languages, shares, color=['b', 'green', 'red', 'yellow']) plt.title('Percentage of users of programming languages') plt.show()
Transparency
Another appearance parameter is alpha
(transparency of the plot). Its default value is 1
(opaque), which is its maximum possible value. Basically, its possible values range from 0
to 1
, where 0
makes the plot fully transparent.
import matplotlib.pyplot as plt import numpy as np data_linear = np.arange(0, 11) data_squared = data_linear ** 2 # Changing the transparency of the first line plot plt.plot(data_linear, label='linear function', color='red', alpha=0.5) plt.plot(data_squared, '-o', label='quadratic function', color='blue') plt.xticks(data_linear) plt.xlabel('x', loc='right') plt.ylabel('y', loc='top', rotation=0) plt.legend() plt.show()
Using alpha=0.5
we made the plot for the linear function more transparent in order to focus more attention on the quadratic function plot. Modifying transparency is mostly used exactly for this purpose.
Swipe to start coding
- Set the color of the lowest bars to
'darkslateblue'
. - Set the color of the middle bars to
'steelblue'
(the argument should follow thelabel
parameter). - Set the transparency of the middle bars to
0.7
(the rightmost argument). - Set the color of the top bars to
'goldenrod'
.
Solution
Thanks for your feedback!