一、简介
无论是科研作图还是前端页面设计,颜色的选择往往是理工男的一大难题。笔者使用“matplotlib”库来随机生成颜色并输出颜色的html码以供选择,大大便捷了广大科研人员及前端开发者。
二、代码内容
import matplotlib.pyplot as plt
import random
# Function to generate a random color in hex format
def random_color():
return "#{:06x}".format(random.randint(0, 0xFFFFFF))
# Generate a list of random colors
num_colors = 5 # You can change this to the number of colors you need
colors = [random_color() for _ in range(num_colors)]
# Output the generated colors in HTML format
for i, color in enumerate(colors):
print(f"Color {i+1}: {color}")
# Sample data for pie chart
data = [10, 20, 30, 25, 15]
# Plotting a pie chart with the random colors
plt.pie(data, colors=colors, wedgeprops={"edgecolor":"black"})
plt.show()