본문 바로가기
데이터 분석/시각화

[Matplotlip] x축 또는 y축 눈금 사이의 축 선(axis line) 색상 변경하기

by 부자 꽁냥이 2022. 7. 16.

안녕하세요~ 꽁냥이에요. 꽁냥이가 StackOverflow를 보다가 공유하면 좋은 내용을 찾아보던 중 축 눈금 사이의 선분 색상을 여러 개로 바꾸는 방법이 있더라고요. 

 

이번 포스팅에서는 축 눈금 사이의 선분 색상을 여러개로 바꾸는 방법을 알아보겠습니다.


   x축 또는 y축 눈금 사이의 선분 색상 바꾸기

먼저 아래 코드는 x축 눈금 사이의 선분 색상을 바꾸는 내용입니다. 핵심은 LineCollection을 이용하여 눈금과 눈금 사이의 선 집합을 구성하고 각 선분의 색상을 지정하는 것입니다. 그리고 기존 x축 지워주고 LineCollection을 x축 앞쪽에 배치하여 적용해주면 됩니다. 나머지 내용은 주석을 참고해주세요.

 

import matplotlib.pyplot as plt
import numpy as np
import random
import seaborn as sns

from matplotlib.collections import LineCollection

random.seed(10)
fig = plt.figure(figsize=(8,8))
fig.set_facecolor('white')
ax = fig.add_subplot()
ax.plot(range(10), [random.randint(0, 5) for _ in range(10)])

## 눈금과 눈금사이는 색상을 변경하되 나머지 부분은 기존 검은색으로 유지한다.
x_lim = ax.get_xlim()
target_xticks = [x for x in ax.get_xticks() if x >= x_lim[0] and x <= x_lim[1]] # 눈금 좌표
total_xticks = target_xticks.copy()

## 눈금 좌표에 x_lim 추가
total_xticks.insert(0, x_lim[0]) 
total_xticks.insert(len(total_xticks), x_lim[-1])
y_coord = [0]*len(total_xticks)

## x축 눈금과 눈금사이는 색상을 지정하고 그 외 색상은 검정색으로 유지
colors = sns.color_palette('hls', len(target_xticks)-1)
colors.insert(0, 'k')
colors.insert(len(colors), 'k')

## 눈금 좌표를 2차원 배열로 변환
points = np.array([total_xticks, y_coord]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)

## LineCollection
lc = LineCollection(segments, # 라인 조각
                    colors=colors, # 라인 색상
                    linewidth=3, # 라인 두께
                    transform=ax.get_xaxis_transform(), # 현재 axes 좌표로 바꿈
                    clip_on=False # 맨앞으로 표시
                   )
ax.add_collection(lc) # LineCollection 추가
ax.spines['bottom'].set_visible(False) # 원래 x축은 제거

plt.show()

 

x축 눈금 사이 색상 변경

 

보시는 바와 같이 눈금 사이의 선분 색상이 바뀐 것을 알 수 있습니다.

 

위와 비슷한 방법으로 y축 눈금 사이 색상을 바꿀 수 있습니다. 아래 코드를 살펴보세요. 위와 동일하므로 설명은 생략합니다.

 

import matplotlib.pyplot as plt
import numpy as np
import random
import seaborn as sns

from matplotlib.collections import LineCollection

random.seed(10)
fig = plt.figure(figsize=(4,8))
fig.set_facecolor('white')
ax = fig.add_subplot()
ax.plot(range(10), [random.randint(0, 5) for _ in range(10)])

## 눈금과 눈금사이는 색상을 변경하되 나머지 부분은 기존 검은색으로 유지한다.
y_lim = ax.get_ylim()
target_yticks = [x for x in ax.get_yticks() if x >= y_lim[0] and x <= y_lim[1]] # 눈금 좌표
total_yticks = target_yticks.copy()

## 눈금 좌표에 y_lim 추가
total_yticks.insert(0, y_lim[0]) 
total_yticks.insert(len(total_yticks), y_lim[-1])
x_coord = [0]*len(total_yticks)

## y축 눈금과 눈금사이는 색상을 지정하고 그 외 색상은 검정색으로 유지
colors = sns.color_palette('hls', len(target_yticks)-1)
colors.insert(0, 'k')
colors.insert(len(colors), 'k')

## 눈금 좌표를 2차원 배열로 변환
points = np.array([x_coord, total_yticks]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)

## LineCollection
lc = LineCollection(segments, # 라인 조각
                    colors=colors, # 라인 색상
                    linewidth=1, # 라인 두께
                    transform=ax.get_yaxis_transform(), # 현재 axes 좌표로 바꿈
                    clip_on=False # 맨앞으로 표시
                   )
ax.add_collection(lc) # LineCollection 추가
ax.spines['left'].set_visible(False) # 원래 y축은 제거

plt.show()

 

y축 눈금 사이 색상 변경


오늘 알아본 내용은 사실 많이 쓰이지 않는 것 같은데요. 그래도 알아두면 언젠가 써먹을 수 있을 것 같아요. 지금까지 꽁냥이의 글 읽어주셔서 감사합니다.

 

참고자료

https://stackoverflow.com/questions/44273365/color-axis-spine-with-multiple-colors-using-matplotlib

 


댓글


맨 위로