matplotlib中具有不同宽度和颜色的条形图(条形Mekko图)

2024-04-26 00:55:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在matplotlib中创建所谓的bar mekko chart。你知道吗

我发现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) ??

Tags: importbinmatplotlibasnpbarcmplt
1条回答
网友
1楼 · 发布于 2024-04-26 00:55:25

看来你已经找到了所有必要的零碎东西,并用错误的方法把它们拼凑在一起。你知道吗

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

相关问题 更多 >