I want to change the bar color of the state: AZ, CA, FL, NY, OH, and OK. I did it by counting the index; however, I am wondering if I can change the color according to the names of the x ticks.
import matplotlib.pylab as plt
fig=plt.figure(figsize=(10,8), dpi= 90)
lists = sorted(frequency_state.items())
x, y = zip(*lists)
bars = plt.bar(x, y, color = 'grey')
plt.grid()
plt.xticks(rotation = 90)
for i in [2,3,5,23,24,25,31]:
bars[i].set_color('r')
plt.show()
{'FL': 45,
'OK': 37,
'OH': 33,
'NY': 28,
'TX': 27,
'CA': 25,
'AZ': 17,
'GA': 10,
'KY': 9,
'MN': 8,
'MA': 8,
'LA': 8,
'PA': 7,
'ID': 7,
'NJ': 6,
'VA': 6,
'IN': 6,
'MT': 6,
'TN': 5,
'CT': 5,
'NC': 5,
'WI': 5,
'MD': 4,
'IL': 4,
'UT': 3,
'IA': 3,
'MI': 3,
'AR': 2,
'MO': 2,
'SC': 2,
'AL': 2,
'NV': 2,
'OR': 1,
'SD': 1,
'ND': 1}
Normalize the value in the colormap you want to display and set it to the desired color of the bar chart.
import matplotlib.pylab as plt
import matplotlib.colors as mcolors
frequency_state = {'FL': 45, 'OK': 37, 'OH': 33, 'NY': 28, 'TX': 27, 'CA': 25, 'AZ': 17, 'GA': 10, 'KY': 9, 'MN': 8,
'MA': 8, 'LA': 8, 'PA': 7, 'ID': 7, 'NJ': 6, 'VA': 6, 'IN': 6, 'MT': 6, 'TN': 5, 'CT': 5, 'NC': 5, 'WI': 5,
'MD': 4, 'IL': 4, 'UT': 3, 'IA': 3, 'MI': 3, 'AR': 2, 'MO': 2, 'SC': 2, 'AL': 2, 'NV': 2, 'OR': 1, 'SD': 1, 'ND': 1}
fig=plt.figure(figsize=(10,8), dpi= 90)
ax = plt.subplot()
colormap = plt.cm.Blues
normalize = mcolors.Normalize(vmin=min(frequency_state.values()), vmax=max(frequency_state.values()))
lists = sorted(frequency_state.items())
x, y = zip(*lists)
bars = plt.bar(x, y, color='grey')
plt.grid()
plt.xticks(rotation = 90)
for i in [2,3,5,23,24,25,31]:
bars[i].set_color(colormap(normalize(lists[i][1])))
plt.show()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.