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

Python 3.x 为什么matplotlib图例元素具有相同的颜色?,python-3.x,matplotlib,bar-chart,legend,Python 3.x,Matplotlib,Bar Chart,Legend,我正在做一个条形图并添加图例。代码如下: 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.

我正在做一个条形图并添加图例。代码如下:

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
print(colors[ii%len(colors)])
rect = ax.bar(ind+ii*0.8, rectArr[ii], 0.18, color=tuple([colors[ii%len(colors)]],), zorder=3)
rects += tuple(rect,)
ii=1
rect = ax.bar(ind+ii*0.8, rectArr[ii], 0.18, color=(colors[ii%len(colors)]), zorder=3)
rects += tuple(rect,)
legends = ("a", "b",)
ax.legend(rects, legends, loc='upper center', bbox_to_anchor=(0.5, -0.08), ncol=3 )
plt.show()
我遇到的问题是,图例元素与下图中的颜色相同:为什么


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

e、 g

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

希望这有帮助

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()
ax.plot(x, v, label='a = red')  #plot one array 
ax.plot(x, v1, label='b =green') #plot 2nd array

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