Python:带有颜色条的条形图 [英] Python: Barplot with colorbar

查看:739
本文介绍了Python:带有颜色条的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to make a bar plot with a color bar, each bar's hight is one variable (y) and each bar should have a color depending on another variable (c).

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

What I've got to is this (simple example):

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处看到一条蓝线,它不应该在那里.

The main problem is that the histogram colors are fine but the color bar is in a diferent scale. besides that I can see a blue line at y=0, it shouldn't be there.

任何帮助都会给您带来帮助. 谢谢!

Any help will be a preciated. Thanks!

推荐答案

您正在条形图中创建一个contourf图.那没有道理.

You are creating a contourf plot inside your bar plot. That makes no sense.

相反,您将需要创建一个没有任何视觉表示的可映射对象以提供给颜色栏.这将是ScalarMappable.

Instead you would need to create a mappable without any visual representation to supply to the colorbar. This would be a 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()

这篇关于Python:带有颜色条的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆