Matplotlib is a powerful plotting library in Python that supports a wide range of visualizations. One of its handy features is the ability to use named colors to enhance the aesthetics of your plots. Named colors provide a convenient way to specify colors without needing to remember color codes. In this tutorial, we'll explore how to use named colors in Matplotlib and provide some practical code examples. ## List of Matplotlib Named Colors Matplotlib provides a comprehensive list of named colors. You can view all the named colors by running the code below. It creates a grid plot displaying all the named colors available in Matplotlib. It serves as a convenient reference for choosing colors for your plots.
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# List all named colors
colors = list(matplotlib.colors.CSS4_COLORS.keys())
# Set up the grid size (adjust rows and columns as needed)
cols = 6 # Number of columns
rows = int(np.ceil(len(colors) / cols)) # Calculate the required number of rows
# Create figure and axes
fig, ax = plt.subplots(figsize=(24, 24))
ax.set_xlim(0, cols)
ax.set_ylim(0, rows * 2) # More space between rows
# Hide axes
ax.set_xticks([])
ax.set_yticks([])
ax.set_frame_on(False)
# Loop through the colors and place them in the grid
for i, color in enumerate(colors):
col = i % cols
row = i // cols
# Create a rectangle with the color as the background
ax.add_patch(plt.Rectangle((col, row * 2 + 0.2), 1, 0.75, color=color)) # Adjust row multiplier for more space
# Add the color name below the rectangle
ax.text(col + 0.5, row * 2 - 0.5, color, ha='center', va='top', fontsize=16, color='black')
plt.title('Matplotlib Named Colors', y=1.03, fontsize=16)
plt.gca().invert_yaxis() # Invert y-axis to make (0,0) the top-left corner
plt.tight_layout()
plt.show()## How to Use Named Colors in Matplotlib Matplotlib comes with a variety of named colors that can be used to customize your plots. These named colors include basics like `red`, `blue`, and `green`, as well as more specific colors like `skyblue` and `springgreen`. Here is a simple example to get you started:
import matplotlib.pyplot as plt
# Sample Data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# Create a plot
plt.plot(x, y, color='skyblue', marker='o')
# Add title and labels
plt.title('Plot with Named Color')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Show the plot
plt.show()In this example, the line graph is created with a skyblue color and circle markers. Let's explore named colors further with different types of plots. ## Named Colors in Different Plot Types ### Scatter Plot
import matplotlib.pyplot as plt
# Sample Data
x = [10, 20, 30, 40, 50]
y = [15, 25, 35, 45, 55]
sizes = [100, 200, 300, 400, 500]
colors = ['red', 'green', 'blue', 'purple', 'orange']
# Create a scatter plot
plt.scatter(x, y, s=sizes, c=colors, alpha=0.6)
# Add title and labels
plt.title('Scatter Plot with Named Colors')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Show the plot
plt.show()### Bar Plot
import matplotlib.pyplot as plt
# Sample Data
categories = ['A', 'B', 'C', 'D', 'E']
values = [3, 7, 5, 6, 4]
# Create a bar plot
plt.bar(categories, values, color='seagreen')
# Add title and labels
plt.title('Bar Plot with Named Colors')
plt.xlabel('Categories')
plt.ylabel('Values')
# Show the plot
plt.show()### Pie Chart
import matplotlib.pyplot as plt
# Sample Data
categories = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
# Create a pie chart
plt.pie(sizes, labels=categories, colors=colors, startangle=140, autopct='%1.1f%%')
# Add title
plt.title('Pie Chart with Named Colors')
# Show the plot
plt.show()