pbj0812의 코딩 일기

[Python] barh 그래프에서 특정 bar만 다른 색으로 칠하기 본문

ComputerLanguage_Program/PYTHON

[Python] barh 그래프에서 특정 bar만 다른 색으로 칠하기

pbj0812 2022. 1. 4. 02:18

0. 목표

 - barh 그래프에서 특정 bar만 다른 색으로 칠하기

1. 실습

 1) library 호출

import pandas as pd
import matplotlib.pyplot as plt

 2) 데이터 생성

df = pd.DataFrame({'catn' : ['a', 'b', 'c', 'd', 'e'], 
			'2020' : [1, 2, 3, 4, 5], 
                    '2021' : [5, 4, 3, 2, 1], 
                    '2022' : [3, 5, 1, 5, 2]})
df_copy = df.copy()

 3) 그림 제작에 사용될 필드명 저장

column_list = df_copy.columns[1:]

 4) 그림 그리기

# 판 깔기
fig, ax = plt.subplots(len(column_list), 1)
# 피규어 크기 조정
fig.set_size_inches(15, 10 * len(column_list))
for i in range(len(column_list)):
    # 필드 명 기준 정렬
    df_copy.sort_values(column_list[i], ascending = True, inplace = True)
    # 인덱스 초기화(찾고자 하는 조건의 인덱스 위치 찾기 위함)
    df_copy.reset_index(drop= True, inplace = True)
    # barh
    bars = ax[i].barh(df_copy['catn'], df_copy[column_list[i]], color = 'blue')
    # 특정 레코드 명 필드만 특정색으로 칠하기
    bars[df_copy[df_copy['catn']=='a'].index[0]].set_color('orange')
    # 꾸미기
    ax[i].set_title(column_list[i], fontsize = 20)
    ax[i].tick_params(axis = 'x', labelsize = 15)
    ax[i].tick_params(axis = 'y', labelsize = 15)

2. 참고

 - python - Matplotlib에서 단일 막대 업데이트

 

Comments