Study/Python

matplotlib에서 임의의(random) color 자동 생성하기 : hex string 기반

13.d_dk 2023. 4. 21. 00:13
728x90
반응형

해결하고자 하는 문제

  • python을 통한 visualization에서 matplotlib에서 랜덤한 color를 생성해야할 때가 있음
  • 임의의 여러 데이터를 color로 표현할 때 color를 일일이 지정하는 것은 비효율적임
  • 랜덤하게 color를 생성하여 입히는 것이 필요함

 

해결 방법 : 랜덤한 hex string 생성 후 color로 변환

  • 여기서 랜덤하게 color hex string를 만들어 이를 기반으로 color를 생성하면 효율적임
  • Matplotlib에서 임의의 color hex string을 생성하려면 matplotlib.colors 모듈을 사용할 수 있음
  • code 예시는 다음과 같음
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import matplotlib.colors as mcolors
import random
 
def generate_random_color():
    """Generate a random color hex string."""
    colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
    color_names = list(colors.keys())
    # Remove white and black colors
    color_names.remove('w')
    color_names.remove('k')
    # Generate a random color name
    color_name = random.choice(color_names)
    # Convert the color name to hex
    color_hex = mcolors.to_hex(colors[color_name])
    return color_hex
 
cs
  • 이 예제 함수에서는 먼저 matplotlib.colors 모듈을 import
  • 이후 Matplotlib의 모든 기본 색상과 CSS4 색상이 포함된 dict을 생성
  • 그런 다음 dict에서 키를 추출하여 color name list를 생성
  • 마지막으로 흰색과 검은색은 무작위 색상 생성에 적합하지 않으므로 list에서 제거
  • 임의의 색상을 생성하려면 color name list에서 color name을 무작위로 선택
  • 이후 mcolors 모듈의 to_hex() 메서드를 사용하여 색상을 hex string로 변환하여 return
  • scatter plot을 통해 이 함수를 테스트하여 볼 수 있음
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
import random
 
def generate_random_color():
    """Generate a random color hex string."""
    colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
    color_names = list(colors.keys())
    # Remove white and black colors
    color_names.remove('w')
    color_names.remove('k')
    # Generate a random color name
    color_name = random.choice(color_names)
    # Convert the color name to hex
    color_hex = mcolors.to_hex(colors[color_name])
    return color_hex
 
# Generate random data
= range(10)
= [i**2 for i in x]
 
# Create a scatter plot with random colors
fig, ax = plt.subplots()
for i in range(len(x)):
    color = generate_random_color()
    ax.scatter(x[i], y[i], c=color, s=50)
 
plt.show()
 
cs
  • 결과는 다음과 같음

 

 

 

 

반응형