Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AayushSameerShah/d30093f63364b02edd3991676c35c0f7 to your computer and use it in GitHub Desktop.
Save AayushSameerShah/d30093f63364b02edd3991676c35c0f7 to your computer and use it in GitHub Desktop.
We are setting the custome cm colors in the matplotlib, most of the time the bars are sorted. But sometimes when the xticks are in the format of Date. Then, the bars are not sorted by their values. So, giving the custome cm will break. Here I am presenting the code which will help to give the custom colors when the bars are ordered by dates.
# Need to make axes
ax = plt.axes()
# Bar plot with sorted index (where the bars will be like |li|liii| ← unsorted
df.value_counts().plot.bar(ax=ax)
# Store individual heights
heights = []
for patch in ax.patches:
heights.append(patch.get_height())
heights = np.array(heights)
# Store colors
colors = cm.Blues(np.linspace(.2, 1, 23))
# Assign colors
for idx, th in enumerate(heights.argsort()):
ax.patches[th].set_facecolor(colors[idx])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment