11.1 C
London
Sunday, July 7, 2024
HomePythonMatplotlib in PythonHow to Modify a Matplotlib Histogram Color (With Examples)

How to Modify a Matplotlib Histogram Color (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories