Skip to content

Instantly share code, notes, and snippets.

@MagicSword
Created December 9, 2019 13:17
Show Gist options
  • Save MagicSword/0f249e1fee4e357b4abe394c92c20ae7 to your computer and use it in GitHub Desktop.
Save MagicSword/0f249e1fee4e357b4abe394c92c20ae7 to your computer and use it in GitHub Desktop.
How to set histogram color as a gradient?
# https://stackoverflow.com/questions/59231945/how-to-set-histogram-color-as-a-gradient
def pretty_hist(data, bins, n_loops=8, alpha=1, base_color=[0.121569, 0.466667, 0.705882]):
N, bins, patches = plt.hist(data, bins=bins, density=True)
bm = bins.max()
bins_norm = bins / bm
bc = base_color
for bin_norm, patch in zip(bins_norm, patches):
grad = np.sin(np.pi * n_loops * bin_norm) / 15 + .04
color = (bc[0] + grad, bc[1] + grad, bc[2] + grad, alpha)
patch.set_facecolor(color)
plt.gcf().set_size_inches(6, 1)
plt.box(None)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(2)
x = 0.06*(np.random.uniform(-1, 1, 8000) + 0.05*np.random.randn(8000))
pretty_hist(x, 400, n_loops=8, alpha=0.9)
pretty_hist(x, 400, n_loops=16, alpha=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment