vary the color of each bar in bargraph using particular value
bar
takes a list of colors as an argument (docs). Simply pass in the colors you want.
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import Normalize
from numpy.random import rand
fig, ax = plt.subplots(1, 1)
# get a color map
my_cmap = cm.get_cmap('jet')
# get normalize function (takes data in range [vmin, vmax] -> [0, 1])
my_norm = Normalize(vmin=0, vmax=5)
# some boring fake data
my_data = 5*rand(5)
ax.bar(range(5), rand(5), color=my_cmap(my_norm(my_data)))
plt.show()
import matplotlib.pyplot as plt
import matplotlib as mp
import numpy as np
xs = "ABCDEFGHI"
ys = [5, 6, 7, 8, 9, 10, 11, 12, 13]
#Colorize the graph based on likeability:
likeability_scores = np.array([
5, 4.5, 3.5,
2.5, 1.5, .5,
2, 3, 4,
])
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, 0),
(1.0, 0, 0)],
"blue": [(0, 0, 0),
(1.0, 0, 0)]
}
)
#Map xs to numbers:
N = len(xs)
x_nums = np.arange(1, N+1)
#Plot a bar graph:
plt.bar(
x_nums,
ys,
align="center",
color=color_map(data_normalizer(likeability_scores))
)
#Change x numbers back to strings:
plt.xticks(x_nums, xs)
plt.show()
--output:--
r,g,b values run from 0-1. Here is the red mapping:
"red": [(0, 1.0, 1.0),
(1.0, .5, .5)],
The first element in each tuple specifies the normalized likeability score. The second element in each tuple specifies the shade of red (0-1). The third element in each tuple is for more complicated stuff, so here it is always the same as the second element.
The red mapping specifies that the normalized likeability scores between 0-1.0 (the first elements of each tuple) will be mapped to the range 100% red to 50% red (the second elements in each tuple). A normalized likeability score of 0 will be mapped to 100% red, and a normalized likeability score of 1.0 will be mapped to 50% red. Setting the darkest red to 50% keeps the red from getting so dark that it looks brown or black.
You can specify as many tuples as you want--you just have to make sure you assign red values for the whole range (0-1) of normalized likeability scores, e.g.:
"red": [(0, .5, .5),
(.8, .6, .6),
(1.0, .9, .9)],
You can't do this:
"red": [(0, .5, .5),
(.8, 1.0, 1.0)],
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame([1,2,3,4], [1,2,3,4])
color = ['red','blue','green','orange']
df.plot(kind='bar', y=0, color=color, legend=False, rot=0)