how to insert text inside bar if bar color equal to purple
So I've this image :
What I trying to do if to leave 'H37Rv' only in the purple bar.
My code is the following:
rects = ax.bar(ind, num, width, color=colors)
for rect in rects:
height = int(rect.get_height())
if height < 5:
yloc = height + 2
clr = '#182866'
else:
yloc = height / 2.0
clr = '开发者_JS百科#182866'
p = 'H37Rv'
xloc = rect.get_x() + (rect.get_width() / 2.0)
ax.text(xloc, yloc, p, horizontalalignment='center', verticalalignment='center', color=clr, weight='bold')
I also tried this:
for rect in rects:
if color == purple:
height = int(rect.get_height())
if height < 5:
yloc = height + 2
clr = '#182866'
but I get an error saying color is not defined.
Anyone has any idea how to solve this?
Thanks a lot!
If you move the last three lines of your first example in one indent level, so they are part of the "else" clause that sets the colour to purple, that should do it.
[Edit: Sorry, I misread slightly. That would also leave the text in the 2nd bar. There's no way to get the colour of a rectangle as far as I know, but you could do:
rects = ax.bar(ind, num, width, color=colors)
rect = rects[-1]
height = int(rect.get_height())
if height < 5:
yloc = height + 2
else:
yloc = height / 2.0
clr = '#182866'
p = 'H37Rv'
xloc = rect.get_x() + (rect.get_width() / 2.0)
ax.text(xloc, yloc, p, horizontalalignment='center', verticalalignment='center', color=clr, weight='bold')
That would set the text in the last bar only.
If it could be any bar that might be purple, not necessarily the last one, well, you've got the list of colours you initialised the rectangles with, so:
rects = ax.bar(ind, num, width, color=colors)
for i in range(len(colors):
if colors[i] == purple: # or however you specified "purple" in your colors list
labelled_rects.append(i)
for i in labelled_rects:
rect = rects[i]
height = int(rect.get_height())
if height < 5:
yloc = height + 2
else:
yloc = height / 2.0
clr = '#182866'
p = 'H37Rv'
xloc = rect.get_x() + (rect.get_width() / 2.0)
ax.text(xloc, yloc, p, horizontalalignment='center', verticalalignment='center', color=clr, weight='bold')
You can get the color of a rectangle with rect.get_facecolor()
, which allows you to place the label the way you want.
Alternatively, since you know which colors you used when drawing the bar plot, and if they are represented by a list, you can indeed easily get the list of purple rectangles.
精彩评论