13
Lesson 13
Customizing plot styles
Objective
By the end of this lesson, students will understand how to use pre-built styles, apply custom styles, and utilize Matplotlib’s color maps and advanced color options to enhance the appearance of their plots.
1. Using Pre-built styles with style.use():
Matplotlib provides a variety of pre-built styles that can change the appearance of your plots quickly. These styles adjust color schemes, fonts, grid lines, and more, to give your plots a consistent and polished look.
Syntax:
By the end of this lesson, students will understand how to use pre-built styles, apply custom styles, and utilize Matplotlib’s color maps and advanced color options to enhance the appearance of their plots.
1. Using Pre-built styles with style.use():
Matplotlib provides a variety of pre-built styles that can change the appearance of your plots quickly. These styles adjust color schemes, fonts, grid lines, and more, to give your plots a consistent and polished look.
Syntax:
import matplotlib.pyplot as plt plt.style.use('style_name')
To see all available styles, use:
print(plt.style.available)
Example: Applying a Pre-built style
import matplotlib.pyplot as plt import numpy as np # Use a pre-built style plt.style.use('ggplot') # Create sample data x = np.linspace(0, 10, 100) y = np.sin(x) # Plot the data plt.plot(x, y) # Show the plot with the selected style plt.title('Plot with ggplot Style') plt.show()
In this example, we apply the 'ggplot' style, which changes the colors and grid appearance to match the look of the popular ggplot2 library in R.
Popular Pre-built styles:
- ggplot
- seaborn
- fivethirtyeight
- bmh
- classic
- dark_background
2. Creating custom styles:
You can create your own custom style by specifying properties such as font size, line width, background color, etc. This allows you to have full control over the visual elements of your plots.
Setting custom parameters
plt.rcParams['lines.linewidth'] = 2 plt.rcParams['axes.titlesize'] = 14 plt.rcParams['axes.labelsize'] = 12
- lines.linewidth : Adjusts the width of lines in the plot.
- axes.titlesize : Sets the font size of the plot title.
- axes.labelsize : Sets the font size of axis labels.
Example: Customizing plot parameters
import matplotlib.pyplot as plt import numpy as np # Customize parameters plt.rcParams['lines.linewidth'] = 3 plt.rcParams['axes.titlesize'] = 16 plt.rcParams['axes.labelsize'] = 12 plt.rcParams['axes.grid'] = True # Create sample data x = np.linspace(0, 10, 100) y = np.cos(x) # Plot the data plt.plot(x, y, color='blue') # Add title and labels plt.title('Customized Plot') plt.xlabel('X-axis') plt.ylabel('Y-axis') # Show the plot plt.show()
In this example:
- We customized the line width and font sizes for the title and labels using plt.rcParams.
- We also turned on grid lines using axes.grid = True.
3. Matplotlib’s colormaps (colormap):
Colormaps in Matplotlib are used to map numeric data to colors. This is especially useful for visualizing data such as heatmaps, scatter plots, and surface plots. Matplotlib provides several pre-defined colormaps that cover a wide range of color schemes.
a. Commonly used colormaps:
- Sequential: viridis, plasma, inferno, magma
- Diverging: coolwarm, PiYG, Spectral
- Cyclic: twilight, twilight_shifted
b. Applying a colormap:
You can apply a colormap using cmap in functions like scatter(), contourf(), or imshow().
Example: Applying a colormap to a scatter plot
import matplotlib.pyplot as plt import numpy as np # Create sample data x = np.random.rand(100) y = np.random.rand(100) colors = np.random.rand(100) # Create a scatter plot with colormap plt.scatter(x, y, c=colors, cmap='viridis') # Add title plt.title('Scatter Plot with Viridis Colormap') # Show the plot plt.colorbar() # Add a colorbar to explain the colormap plt.show()
In this example:
- We applied the 'viridis' colormap to a scatter plot.
- The colorbar() function adds a legend to explain the meaning of the colors.
c. Using Colormap with imshow() for heatmaps
data = np.random.rand(10, 10) # Display data as a heatmap plt.imshow(data, cmap='plasma') plt.title('Heatmap with Plasma Colormap') plt.colorbar() # Add a colorbar to the heatmap plt.show()
4. Advanced color options:
Matplotlib also allows for more advanced customization of colors, including specifying colors manually, using hexadecimal values, and working with transparency (alpha).
a. Specifying custom colors:
You can specify colors for plots using:
- Color names ('blue', 'red')
- Hexadecimal codes ('#FF5733')
- RGB/RGBA values ((0.1, 0.2, 0.5, 0.8))
b. Setting transparency with alpha:
The alpha parameter controls the transparency of plot elements, with alpha=0 being fully transparent and alpha=1 being fully opaque.
Example: Custom colors and alpha
import matplotlib.pyplot as plt import numpy as np # Create sample data x = np.linspace(0, 10, 100) y1 = np.sin(x) y2 = np.cos(x) # Plot with custom colors and alpha plt.plot(x, y1, color='#FF5733', alpha=0.8, label='Sine Wave') plt.plot(x, y2, color='blue', linestyle='--', alpha=0.6, label='Cosine Wave') # Add title, labels, and legend plt.title('Plot with Custom Colors and Transparency') plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.legend() # Show the plot plt.show()
In this example:
- We used a custom hexadecimal color ('#FF5733') and set transparency (alpha) for both lines.
- One line is solid and the other is dashed (linestyle='--').
5. Exercises:
Exercice: 1
1. Choose a pre-built style from Matplotlib (e.g., 'seaborn-darkgrid') and apply it to a plot.
2. Use a scatter plot with random points and customize the plot title and labels.
Exercice: 2
1. Set custom parameters for line width, grid lines, and title font size.
2. Plot a sine wave and a cosine wave on the same plot using different line colors.
Exercice: 3
1. Create a scatter plot with 200 points using random data.
2. Apply the 'inferno' colormap and display a colorbar.
Exercice: 4
1. Plot a sine wave with a custom color (hexadecimal) and an alpha value of 0.7.
2. Overlay a cosine wave with a different color and transparency.
Exercice: 5
1. Generate a 10x10 random matrix and visualize it using imshow().
2. Apply the 'coolwarm' colormap and display a colorbar.
Conclusion
In this lesson, we explored various ways to customize the appearance of Matplotlib plots. We learned how to use pre-built styles with style.use(), create custom styles by modifying rcParams, and apply colormaps for advanced color visualization. Customizing plots helps improve their readability and presentation, making it easier to convey information effectively.