Matplotlib hist 为不同的柱添加不同的颜色
在Matplotlib
中,ax.hist
的color
参数默认为所有的bins添加同样的颜色。那么,如何给不同的bin添加不一样的颜色呢?
Code
fig, ax = plt.subplots(figsize=(12, 6), tight_layout=True)
cm = plt.cm.get_cmap('Greens')
n, bins, patches = ax.hist(x*100, 500, density=True, cumulative=-1, color='green', histtype='bar')
ax.set_xlim(0, 20)
for c, p in zip(n, patches):
plt.setp(p, 'facecolor', cm(1-c))
plt.show()
Result
Reference
- Bas Swinckels. (Jan 3, 2022). Plot histogram with colors taken from colormap. Retrieved from https://stackoverflow.com/questions/23061657/plot-histogram-with-colors-taken-from-colormap