Matplotlib Color Gradients

Brendan Artley
3 min readApr 25, 2022

--

Color Gradient

Data visualization is so important as it enables technical individuals to share their ideas in a language that others can understand. This is especially true in Computer Science and Machine Learning as engineers need to communicate their work with technical business leaders.

In this article, we will showcase a custom color gradient function that can be applied to Matplotlib plots. Color gradients are a feature that can be added to plots to make them more visually appealing to readers. We will also use the Titanic Dataset and random data to create sample visualizations.

Gradient Functions

The following two functions work in tandem to create a color gradient that is easily understood by Matplotlib.

hex_to_rgb

  • This function takes in a color’s hexadecimal value and converts it to an RGB color scheme.

get_color_gradient

  • This function takes in two hexadecimal color values and a number. It then returns an array of the colors necessary to blend the two input colors.

Example #1: Bar Chart

The Titanic dataset is a simple tabular dataset that is great for practicing various data visualization ideas. We will use this dataset here.

In the following cell, we are first loading the Titanic dataset into Pandas. Then, we are creating a dictionary of the age counts in the dataset.

In the next cell, we use a simple bar chart to visualize the passenger age count. Using the get_color_gradient function into the color parameter we get a nice smooth gradient between the two colors. Cool!

Bar Plot w/ Gradient

Example #2: Pie Chart

We can also use the color gradient function with a pie chart. In the following plot, we use some dummy data, which consists of 50 pieces that are all equal to 2% of the pie to showcase a smooth gradient.

Note: It is best practice to use a pie chart for under 5 pie slices, but in this case, we are just using the pie plot to showcase the gradient function.

Pie Plot w/ Gradient

Example #3: Scatter Plot

The final plot that we are going to use is the scatter plot. Using Numpy’s random module we can create some dummy data to visualize the change in gradient in points on the plot.

Scatter Plot w/ Gradient

Feel free to copy the linked notebook and try out different gradients for yourself.

Hopefully, you use the gradient functions to make more visually appealing plots that come across as more professional.

Any constructive criticism or feedback on the article or notebook is greatly appreciated!

--

--