我正在尝试在matplotlib中创建bar mekko chart。
我发现matplotlib中的条形图可以解决这个问题,但是我错过了如何显示以0为中心的颜色条。
这是我的尝试,评论了我仍然缺少的摘录:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.cm as cm
%matplotlib inline
x = np.array([0. , 0.4512135, 0.760715 , 0.775948 , 0.977063 , 1.170482 ,
1.229812 , 1.3009845, 1.347207 , 1.4155705, 1.928897 ])
bin_width = np.diff(x)
y = np.array([ 0.40048296, 1.11131896, 0.30525134, 3.86793415, 21.80974083,
11.88354534, 13.84599687, 9.7484865 , 9.5418679 , 22.39983675])
z = np.array([0. , 0.4512135, -0.760715 , 0.775948 , 0.977063 , 1.170482 ,
1.229812 , 1.3009845, 1.347207 , -1.4155705])
fig, ax1 = plt.subplots(1)
#?# offset = mcolors.DivergingNorm(vcenter=0.)
# Colorbar needs to be centered (0 should be yellow always)
colors = plt.cm.RdYlBu(z) # offset???
bar_plot = ax1.bar(x[:-1],y,
color=colors,
width=bin_width,
align='edge')
#?# sm = cm.ScalarMappable(cmap=my_cmap, norm=plt.Normalize(0,max(data_color)))
#?# sm.set_array([])
#?# cbar = plt.colorbar(sm)
plt.ylabel("y")
plt.show()
# plt.colorbar(mappable=bar_plot, ax=ax1) ??
答案 0 :(得分:2)
似乎您已经找到了所有必要的点点滴滴,并以错误的方式将它们修补在一起。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.cm as cm
x = np.array([0. , 0.4512135, 0.760715 , 0.775948 , 0.977063 , 1.170482 ,
1.229812 , 1.3009845, 1.347207 , 1.4155705, 1.928897 ])
bin_width = np.diff(x)
y = np.array([ 0.40048296, 1.11131896, 0.30525134, 3.86793415, 21.80974083,
11.88354534, 13.84599687, 9.7484865 , 9.5418679 , 22.39983675])
z = np.array([0. , 0.4512135, -0.760715 , 0.775948 , 0.977063 , 1.170482 ,
1.229812 , 1.3009845, 1.347207 , -1.4155705])
fig, ax = plt.subplots()
cmap = plt.cm.RdYlBu
norm = mcolors.DivergingNorm(vmin=z.min(), vcenter=0., vmax=z.max())
sm = cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
bar_plot = ax.bar(x[:-1], y, color=cmap(norm(z)), width=bin_width, align='edge')
cbar = fig.colorbar(sm)
ax.set_ylabel("y")
plt.show()