条形图颜色取决于Matplotlib中的值

时间:2015-07-22 21:35:01

标签: python matplotlib

我创建了一个条形图,如下所示:

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt

#self.Data1 is an array containing all the data points, inherited from a separate class

DataSet = range(46)
self.Figure1 = plt.figure()
self.Figure1.patch.set_alpha(0)
self.Canvas1 = FigureCanvas(self.Figure1)

#Add canvas to pre-existing Widget#
self.Widget.addWidget(self.Canvas1)
self.Ax1 = plt.subplot(1, 1, 1, axisbg='black')
self.Ax1.bar(DataSet, self.Data1, width=1, color='r')
self.Ax1.tick_params(axis='y', colors='white')
plt.title('GRAPH TITLE', color='w', fontsize=30, fontname='Sans Serif', fontweight='bold')
self.Figure1.tight_layout()

这很好用,产生如下图:

Current graph

我想要做的是根据值设置条形颜色。即如果值为正,则为蓝色;如果值为负,则为红色。最简单的方法是什么?我需要创建颜色映射吗?

2 个答案:

答案 0 :(得分:8)

您也可以将arraylike指定为颜色kwarg:

x = np.arange(1,100)
y = np.sin(np.arange(1,100))
colors = np.array([(1,0,0)]*len(y))
colors[y >= 0] = (0,0,1)
plt.bar(x,y,color = colors)

只要颜色与y的长度相同,您就可以根据需要指定颜色。

enter image description here

或者是一位有点发烧友的人:

x = np.arange(1,100)
y = np.sin(3*np.arange(1,100))
colors = np.array([(1,0,0)]*len(y))
colors[y >= 0] = (0,0,1)
mult = np.reshape(np.repeat(np.abs(y)/np.max(np.abs(y)),3),(len(y),3))
colors =  mult*colors
plt.bar(x,y,color = colors)

enter image description here

答案 1 :(得分:3)

到目前为止,这不是可重用性和/或可扩展性方面的最佳解决方案,但如果您只想要负数字的红色条和正数的蓝色条,您可以通过过滤值来调用条形图两次在手之前。这是我的意思的最小例子:

import numpy as np
import matplotlib.pylab as pl

array = np.random.randn(100)
greater_than_zero = array > 0
lesser_than_zero = array < 0
cax = pl.subplot(111)
cax.bar(np.arange(len(array))[greater_than_zero], array[greater_than_zero], color='b')
cax.bar(np.arange(len(array))[lesser_than_zero], array[lesser_than_zero], color='r')

result http://img11.hostingpics.net/pics/547091download.png