为什么matplotlib图例元素具有相同的颜色?

时间:2019-04-15 16:13:18

标签: python-3.x matplotlib bar-chart legend

我正在制作条形图并添加图例。代码如下:

from tensorflow.keras import backend as K
def custom_accuracy(y_true, y_pred):
    y_true_np = K.eval(y_true)
    y_pred_np = K.eval(y_pred)

我遇到的问题是,图例元素的颜色与下图中的颜色相同:为什么?

enter image description here

2 个答案:

答案 0 :(得分:1)

要获得两种颜色,您只需要修改图例的绘制方式

例如

ax.plot(x, v, label='a = red')  #plot one array 
ax.plot(x, v1, label='b =green') #plot 2nd array

#ax.legend()..
plt.show()

有关更多示例,请参见我的other similar answer

希望这会有所帮助

答案 1 :(得分:0)

import numpy as np
import matplotlib.pyplot as plt
rectArr = list()
fig, ax_arr = plt.subplots(nrows=2, ncols=1, figsize=(8,8), constrained_layout=True)
fig.suptitle("MicCheck")
v = [0,1,2]
v1 = [1,2,3]
rectArr.append(v)
rectArr.append(v1)
rects = tuple()
ax = ax_arr[0]
ind = np.arange(len(v))
colors = ["seagreen", "red", "b", "g", "y"]
ii = 0
legends = ("a", "b",)

print(colors[ii%len(colors)])
rect = ax.bar(ind+ii*0.8, rectArr[ii], 0.18, color=tuple([colors[ii%len(colors)]],), zorder=3, label=legends[0])
rects += tuple(rect,)
ii=1
rect = ax.bar(ind+ii*0.8, rectArr[ii], 0.18, color=(colors[ii%len(colors)]), zorder=3, label=legends[1])
rects += tuple(rect,)
patches, labels = ax.get_legend_handles_labels()
#ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.08), ncol=3 )
ax.legend(patches, legends, loc='upper center' )
plt.show()