Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to set color in matplotlib

Understanding Colors in Matplotlib

When you're starting to learn programming, especially data visualization, you'll quickly encounter the need to customize the look of your plots. Matplotlib, a popular Python library for plotting, provides a multitude of ways to set colors in your charts. Let's dive into the colorful world of Matplotlib without overwhelming you with technical jargon.

Basic Color Customization

To begin with, colors can be set in Matplotlib using color names or hex color codes. A color name is simply a word that represents a color, like 'red' or 'blue'. A hex color code is a hashtag followed by a combination of six letters and/or numbers, like #FF5733, which represents a particular shade of orange.

Setting Color for a Single Plot Element

Imagine you're drawing with colored pencils. You have a pencil for each part of your drawing. In Matplotlib, you can similarly set the color for each element of your plot. Here's a simple example where we set the color of a line plot:

import matplotlib.pyplot as plt

# Plotting a line with a specific color
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], color='purple')
plt.show()

In this code snippet, we've drawn a line that connects the points (1,1), (2,4), (3,9), and (4,16). We've used the color parameter and set it to 'purple'.

Using Hex Color Codes

Sometimes, you might want a specific shade that isn't available as a named color. This is where hex codes come in handy. Here's how you can use a hex code:

# Plotting a line with a hex color code
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], color='#00FF00') # This is a bright green
plt.show()

Colors for Multiple Elements

What if you're drawing a garden and want different colors for each flower? In Matplotlib, you can set different colors for each element of your plot. Let's say you want to plot two lines with different colors:

# Plotting two lines with different colors
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], color='pink')
plt.plot([1, 2, 3, 4], [2, 3, 5, 10], color='skyblue')
plt.show()

Now you have two lines in your plot, one pink and one sky blue.

Going Beyond Basic Colors

Using RGBA Tuples

Sometimes you want to get more creative and have even more control over the colors, including their transparency. RGBA stands for red, green, blue, and alpha. The first three values are for the color, and the alpha value controls the transparency.

Here's how you can use an RGBA tuple:

# Plotting with RGBA tuples
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], color=(0.1, 0.2, 0.5, 0.3)) # A semi-transparent blue
plt.show()

In this example, (0.1, 0.2, 0.5, 0.3) represents a blue color with some transparency.

Using Colormaps

Imagine a painter who uses a palette of colors that blend into each other. Matplotlib has something similar called colormaps. A colormap is a range of colors that Matplotlib can automatically apply to your data. They are great for representing different ranges of data, like elevation on a map or temperature.

Here's how you can apply a colormap to a scatter plot:

import numpy as np

# Creating some data
x = np.random.rand(50)
y = np.random.rand(50)
colors = np.random.rand(50)  # This will provide a color intensity based on data

# Plotting with a colormap
plt.scatter(x, y, c=colors, cmap='viridis')
plt.colorbar()  # This adds a color bar to the side of the plot
plt.show()

In this scatter plot, each point has a color based on its value in the colors array, using the 'viridis' colormap.

Setting Colors in Bar Charts and Pie Charts

Bar Charts

Bar charts are like skyscrapers in a city skyline, each potentially a different color. Here's how you can set colors in a bar chart:

# Data for the bar chart
categories = ['A', 'B', 'C', 'D']
values = [10, 20, 30, 40]

# Plotting a bar chart with custom colors
plt.bar(categories, values, color=['firebrick', 'green', 'blue', 'purple'])
plt.show()

Each bar in the chart will be a different color, as specified in the list.

Pie Charts

A pie chart is like a real pie with different flavors (colors) for each slice. Setting colors in a pie chart is straightforward:

# Data for the pie chart
labels = ['Apples', 'Bananas', 'Cherries', 'Dates']
sizes = [15, 30, 45, 10]

# Plotting a pie chart with custom colors
plt.pie(sizes, labels=labels, colors=['red', 'yellow', 'pink', 'brown'])
plt.axis('equal')  # This makes the pie chart look circular
plt.show()

Each slice of the pie chart will be colored as specified in the colors list.

Advanced Color Customization

Sometimes you might want to create your own custom colormap or modify existing ones. This is more advanced and requires a deeper understanding of Matplotlib, but just know that it's possible and can be a powerful way to represent your data visually.

Conclusion: The Rainbow at Your Fingertips

In the end, setting colors in Matplotlib is like painting on a digital canvas. You have a vast spectrum of colors to choose from, and you can apply them to your plots in many ways. Whether you're using named colors, hex codes, RGBA tuples, or colormaps, you have the tools to make your data visualizations not only informative but also visually appealing. As you become more comfortable with Matplotlib, you'll find that these color settings are just the beginning of creating art with data. So go ahead, experiment with the rainbow at your fingertips, and let your data shine in the hues that tell its story best.