user32185 user32185 - 3 months ago 12
Python Question

Bar plot width inconsistency

please don't be too harsh.
Could someone explain me why the colors of bars in these two plots are so different?

import numpy as np
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import rcParams

rcParams.update({'figure.autolayout': True})
plt.style.use('ggplot')

def plot3():
bal=np.cumsum(ret)
ind = np.arange(len(ret))
fig, ax = plt.subplots()
barlist=ax.bar(ind,ret,label="Return")
ax.plot(ind,bal,color='b',label="Balance")
for i in ind:
if ret[i]>=0:
barlist[i].set_color('g')
else:
barlist[i].set_color('r')
ax.legend(loc='best',frameon=False)
plt.show()

def plot3b():
bal=np.cumsum(ret)
ind = np.arange(len(ret))
fig, ax = plt.subplots()
colors=['g' if r>=0 else 'r' for r in ret]
ax.bar(ind,ret,color=colors,label="Return")
ax.plot(ind,bal,color='b',label="balance")
ax.legend(loc='best',frameon=False)
plt.show()


In my laptop given

n=100
ret=np.random.randn(n)
ret=np.insert(ret,0,0)


the plots are respectively

plot3

and

plot3b

Answer

Bars have both facecolor and edgecolor, see the docs here.

It seems that set_color() sets both edge and face colour of the bar, so in your first chart the bars are wider that in your second, where the edge colour has not been set

If you change:
ax.bar(ind,ret,color=colors,label="Return")

To:
ax.bar(ind,ret,color = colors, edgecolor = colors, label="Return")

...then both plots are the same:

plot3() enter image description here

plot3b() enter image description here

Please excuse the different spellings of color/colour in this post. Im in the UK, and it just feels wrong to spell colour without the 'u', so I've spelled it "correctly"* when not referencing a function argument.

*That's humour, BTW. So please don't start an American / British English war.

Comments