Python ProgrammingPython Programming

Bar chart with different color of bars

Bar chart with color gradient

import matplotlib.pyplot as plt
import matplotlib as mp
import numpy as np

data = [8, 6, 7, 12, 9, 10, 5, 8, 9]

# Colorize the graph based on likeability:
likeability_scores = np.array(data)

data_normalizer = mp.colors.Normalize()
color_map = mp.colors.LinearSegmentedColormap(
    "my_map",
    {
        "red": [(0, 1.0, 1.0),
                (1.0, .5, .5)],
        "green": [(0, 0.5, 0.5),
                  (1.0, 0, 0)],
        "blue": [(0, 0.50, 0.5),
                 (1.0, 0, 0)]
    }
)

# Map xs to numbers:
N = len(data)
x_nums = np.arange(1, N+1)

# Plot a bar graph:
plt.bar(
    x_nums,
    data,
    align="center",
    color=color_map(data_normalizer(likeability_scores))
)

plt.xticks(x_nums, data)
plt.show()


The following is the output that will be obtained:


Bar chart with different color of bars