1

I am doing a bar plot and adding the legends. The code is the following:

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()

The problem I am getting is that the legend elements have the same colour as in the image below: why is that?

enter image description here

roschach
  • 8,390
  • 14
  • 74
  • 124

2 Answers2

2

To attain both colours, you just need to amend how you're plotting the legend

e.g.

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

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

See my other similar answer for more examples.

Hope this helps

Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81
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()
roschach
  • 8,390
  • 14
  • 74
  • 124