Skip to content

Instantly share code, notes, and snippets.

@wenijinew
Created September 25, 2023 19:11
Show Gist options
  • Save wenijinew/826682e56059107c4cc1cc4c1c57bcf2 to your computer and use it in GitHub Desktop.
Save wenijinew/826682e56059107c4cc1cc4c1c57bcf2 to your computer and use it in GitHub Desktop.
Generate Random Colours
def generate_random_colors(
min_color=0,
max_color=231,
base_colors_total=7,
lighter_colors_total=24,
plot=False,
):
"""Generate random color hex codes.
Firstly, it will generate random integer from min_color (0-(255 - lighter_colors_total - 1)) to max_color (0-(255 - lighter_colors_total)).
The max_color should be less than (255 - lighter_colors_total) because it needs the room to generate lighter colors.
To generate darker colors, use smaller value for max_color.
To generate ligher colors, use bigger value for min_color.
It's recommended to use default values.
If you want to make change, please make sure what you are doing.
Secondly, it will generate 'lighter_colors_total' different hex color codes from base color to the lightest color.
Note that 'lighter_colors_total' includes base color also. It means it will generate 'lighter_colors_total - 1' lighter colors besides base color.
Parameters:
min_color - minimum color code. default: 0.
max_color - maximum color code. default: 254.
base_colors_total - how many base colors to generate. default: 7.
lighter_colors_total - how many lighter colors to generate. default: 24.
plot: True to plot the generated color. Otherwise, False. default: False.
Retrun:
Generated random base colors and all lighter colors of each base color.
The returned value is a two-dimention list. First dimention length is the value of base_colors_total. Second dimention length is lighter_colors_total.
"""
random_int = random.randint(0, 15**6)
_min = min_color
_max = max_color
random_color_code = "#"
for c in range(0, 3):
random_int = random.randint(_min, _max)
random_color = padding(hex(random_int), 2)
random_color_code = random_color_code + random_color
base_colors = generate_xadic_colors(random_color_code, base_colors_total)[
0:base_colors_total
]
if plot:
plt.figure(figsize=(18, 1))
for i, color in enumerate(base_colors):
plt.bar(i, 10, 0.8, color=color)
plt.show()
random_colors = []
for base_color in base_colors:
lighter_colors = generate_lighter_color(
base_color, lighter_colors_total
)
random_colors.append(lighter_colors)
if plot:
plt.figure(figsize=(18, 1))
for i, color in enumerate(lighter_colors):
plt.bar(i, 10, 0.8, color=color)
plt.show()
return random_colors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment