我创建了一个条形图,如下所示:
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()
这工作得很好,生成了下图:
我想做的是根据值设置条形颜色。 IE。如果值为正则为蓝色,如果值为负则为红色。最简单的方法是什么?我需要创建颜色图吗?
请您参考如下方法:
你也可以像这样指定一个数组作为颜色 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 的长度相同,您就可以根据需要指定颜色。
或者更高级的东西:
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)
