gpt4 book ai didi

python - matplotlib 中不同宽度和颜色的条形图(Bar Mekko 图)

转载 作者:行者123 更新时间:2023-12-01 00:43:36 24 4
gpt4 key购买 nike

我正在尝试创建所谓的 bar mekko chart在 matplotlib 中。

我发现 matplotlib 中的条形图可以解决这个问题,但我缺少如何显示以 0 为中心的值的颜色条。

这是我的尝试,评论了我仍然缺少的片段:

example

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) ??

最佳答案

似乎您已经找到了所有必要的零碎内容,并以错误的方式将它们修补在一起。

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()

关于python - matplotlib 中不同宽度和颜色的条形图(Bar Mekko 图),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57164333/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com