How to Modify a Matplotlib Histogram Color (With Examples)


You can use the following basic syntax to modify the color of a histogram in Matplotlib:

plt.hist(data, color = "lightblue", ec="red")

where:

  • data: The name of the data to use for the histogram
  • color: The fill color for the bars in the histogram
  • ec: The edge color for the bars in the histogram

The following example shows how to use this syntax in practice.

Example: Modifying a Matplotlib Histogram Color

Suppose we have the following list of values:

#define list of data
data = [2, 4, 4, 5, 6, 6, 7, 8, 9, 9, 9, 10, 12, 12, 14]

We can use the following basic syntax to create a Matplotlib histogram to visualize the values in this dataset:

import matplotlib.pyplot as plt

#create histogram
plt.hist(data)

By default, Matplotlib creates a histogram with a dark blue fill color and no edge color.

However, we can use the following syntax to change the fill color to light blue and the edge color to red:

import matplotlib.pyplot as plt

#create histogram with light blue fill color and red edge color
plt.hist(data, color = "lightblue", ec="red")

The new histogram has a light blue fill color and a red edge color.

You can also use the lw argument to modify the line width for the edges of the histogram:

import matplotlib.pyplot as plt

#create histogram
plt.hist(data, color = "lightblue", ec="red", lw=5)

The larger the value you use for lw, the thicker the edges on the bars will be.

Note: You can find the complete documentation for the Matplotlib hist function here.

Additional Resources

The following tutorials explain how to perform other common operations in Python:

How to Create a Histogram from Pandas DataFrame
How to Plot Histogram from List of Data in Python

Leave a Reply

Your email address will not be published.