Python:带颜色条的条形图

问题描述 投票:0回答:2

我正在尝试用颜色条制作条形图,每个条形的高度是一个变量(y),每个条形应该具有取决于另一个变量(c)的颜色。

我要做的是这个(简单的例子):

data_x = [0,1,2,3]
data_hight = [60,60,80,100]
data_color = [1000,500,1000,900]


data_color = [x / max(data_color) for x in data_color]
fig, ax = plt.subplots(figsize=(15, 4))

my_cmap = plt.cm.get_cmap('GnBu')
colors = my_cmap(data_color)
rects = ax.bar(data_x, data_hight, color=colors)

CS = plt.contourf([data_x, data_color],cmap=my_cmap)

cbar = plt.colorbar(CS, cmap=my_cmap)
cbar.set_label('Color', rotation=270,labelpad=25)

plt.xticks(data_x)    
plt.ylabel("Y")

plt.show()

主要问题是直方图颜色很好,但颜色条的比例不同。除此之外,我可以在 y=0 处看到一条蓝线,它不应该在那里。

任何帮助将不胜感激。 谢谢!

python matplotlib bar-chart data-visualization colorbar
2个回答
28
投票

您正在条形图中创建一个

contourf
图。这没有任何意义。

相反,您需要创建一个不带任何视觉表示的可映射对象来提供给颜色栏。这将是一个

ScalarMappable

import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable

data_x = [0,1,2,3]
data_hight = [60,60,80,100]
data_color = [1000.,500.,1000.,900.]


data_color = [x / max(data_color) for x in data_color]
fig, ax = plt.subplots(figsize=(15, 4))

my_cmap = plt.cm.get_cmap('GnBu')
colors = my_cmap(data_color)
rects = ax.bar(data_x, data_hight, color=colors)

sm = ScalarMappable(cmap=my_cmap, norm=plt.Normalize(0,max(data_color)))
sm.set_array([])

cbar = plt.colorbar(sm)
cbar.set_label('Color', rotation=270,labelpad=25)

plt.xticks(data_x)    
plt.ylabel("Y")

plt.show()

enter image description here


0
投票

对于高于 ~3.6 的 matplotlib 版本,为了避免“ValueError: Unable to certain Axes tosteal space for Colorbar”错误,您需要指定颜色条的轴,这可以通过 plt.gca() 完成:

import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable

data_x = [0,1,2,3]
data_hight = [60,60,80,100]
data_color = [1000.,500.,1000.,900.]


data_color = [x / max(data_color) for x in data_color]
fig, ax = plt.subplots(figsize=(15, 4))

my_cmap = plt.get_cmap('GnBu') # plt.cm.get_cmap is deprecated as of v3.7
colors = my_cmap(data_color)
rects = ax.bar(data_x, data_hight, color=colors)

sm = ScalarMappable(cmap=my_cmap, norm=plt.Normalize(0,max(data_color)))
sm.set_array([])

cbar = plt.colorbar(sm, ax = plt.gca()) # Supply the current axes to the colorbar
cbar.set_label('Color', rotation=270,labelpad=25)

plt.xticks(data_x)    
plt.ylabel("Y")

plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.