Suppose I have a vertical bar plot like this:
MWE per this suggestion:
JavaScript
x
22
22
1
import numpy as np
2
import matplotlib.pyplot as plt
3
4
fig, ax = plt.subplots()
5
6
bar = ax.bar([1,2,3,4,5,6],[4,5,6,3,7,5], bottom=[1,7,4,6,3,2])
7
8
def gradientbars(bars):
9
grad = np.atleast_2d(np.linspace(0,1,256)).T
10
ax = bars[0].axes
11
lim = ax.get_xlim()+ax.get_ylim()
12
for bar in bars:
13
bar.set_zorder(1)
14
bar.set_facecolor("none")
15
x,y = bar.get_xy()
16
w, h = bar.get_width(), bar.get_height()
17
ax.imshow(grad, extent=[x,x+w,y,y+h], aspect="auto", zorder=0)
18
ax.axis(lim)
19
20
gradientbars(bar)
21
plt.show()
22
Is there an easy way to color the bars with a colormap according to the y-values they actually span (suppose my color bar goes from 1-12 where 1 is represented by yellow and 12 is represented by dark-blue)?
I have tried to adapt this example but wasn’t successful.
Advertisement
Answer
Here is the code in this post adapted such that each bar shows a corresponding slice of the gradient.
JavaScript
1
27
27
1
import numpy as np
2
import matplotlib.pyplot as plt
3
4
fig, ax = plt.subplots()
5
6
x = np.arange(35)
7
bar = ax.bar(x, 6 - np.sin(x / 10) * 3, bottom=5 - np.cos(x / 10) * 5)
8
plt.xlim(x[0] - 0.5, x[-1] + 0.5)
9
10
11
def gradientbars_sliced(bars):
12
ax = bars[0].axes
13
xmin, xmax = ax.get_xlim()
14
ymin, ymax = ax.get_ylim()
15
for bar in bars:
16
bar.set_zorder(1)
17
bar.set_facecolor("none")
18
x, y = bar.get_xy()
19
w, h = bar.get_width(), bar.get_height()
20
grad = np.linspace(y, y + h, 256).reshape(256, 1)
21
ax.imshow(grad, extent=[x, x + w, y, y + h], aspect="auto", zorder=0, origin='lower',
22
vmin=ymin, vmax=ymax, cmap='magma')
23
ax.axis([xmin, xmax, ymin, ymax])
24
25
gradientbars_sliced(bar)
26
plt.show()
27