2 분 소요

1. Bar color demo

import matplotlib.pyplot as plt
fig, ax = plt.subplots()

fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
bar_labels = ['red', 'blue', '_red', 'orange'] # 밑줄 있는 레이블 범례 표시 안함
bar_colors = ['tab:red', 'tab:blue', 'tab:red', 'tab:orange'] # tab을 사용하여 내장된 컬러맵에서 색상 선택

ax.bar(fruits, counts, label = bar_labels, color = bar_colors)

ax.set_ylabel('fruit supply') # y축 레이블
ax.set_title('Fruit supply by kind and color') # 그래프 제목
ax.legend(title = 'Fruit color') # 범례 생성 및 제목 설정

plt.show()

2023-06-19-barcolor_1_0

2. Bar Label Demo

import matplotlib.pyplot as plt
import numpy as np
species = ('Adelie', 'Chinstrap', 'Gentoo') # 펭귄 종류 튜플
sex_counts = {
    'Male': np.array([73, 34, 61]),
    'Female': np.array([73, 34, 58])
}
width = 0.6 # 막대의 너비

fig, ax = plt.subplots() # 그림, 서브플롯 생성
bottom = np.zeros(3) # 막대의 바닥 위치, 초기값은 0

for sex, sex_count in sex_counts.items(): # 각 펭귄 종류 반복
    p = ax.bar(species, sex_count, width, label = sex, bottom = bottom)
    bottom += sex_count

    ax.bar_label(p, label_type = 'center') # 레이블 막대 중앙 위치

ax.set_title('Number of penguins by sex')
ax.legend()

plt.show()

2023-06-19-barcolor_4_0

# Fixing random state for reproducibility
np.random.seed(19680801) # 난수 발생 시드 설정, 난수 재현 가능

# 예시 데이터
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people)) # 성능 데이터 생성
error = np.random.rand(len(people)) # 오차 데이터 생성(0~1)

fig, ax = plt.subplots()

hbars = ax.barh(y_pos, performance, xerr = error, align = 'center')
ax.set_yticks(y_pos, labels = people)
ax.invert_yaxis() # y축 방향 뒤집기
ax.set_xlabel('Performance') # x축 레이블
ax.set_title('How fast do you want to go today?') # 그래프 제목

# Label with specially formatted floats
ax.bar_label(hbars, fmt = '%.2f') # 막대 레이블 표시
ax.set_xlim(right = 15) # x축 범위 설정

plt.show()

2023-06-19-barcolor_5_0

ax 서브플롯 객체의 barh 메서드를 호출하여 수평 막대 그래프를 생성합니다. y_pos는 막대의 위치를 설정하는 데이터입니다. performance는 막대의 길이를 설정하는 데이터입니다. xerr 매개변수를 사용하여 막대의 오차를 설정합니다. align 매개변수를 center로 설정하여 막대를 중앙에 정렬합니다. hbars 변수에 생성된 막대 객체를 할당합니다.

fig, ax = plt.subplots()

hbars = ax.barh(y_pos, performance, xerr = error, align = 'center')
ax.set_yticks(y_pos, labels = people)
ax.invert_yaxis()
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

ax.bar_label(hbars, labels = [f{e:.2f}' for e in error],
             padding = 8, color = 'b', fontsize = 14) # padding: 레이블과 막대 사이 여백
ax.set_xlim(right = 16)

plt.show()

2023-06-19-barcolor_7_0

fruit_names = ['Coffee', 'Salted Caramel', 'Pistachio']
fruit_counts = [4000, 2000, 7000]

fig, ax = plt.subplots()
bar_container = ax.bar(fruit_names, fruit_counts)
ax.set(ylabel = 'pints sold', title = 'Gelato sales by flavor', ylim = (0, 8000))
ax.bar_label(bar_container, fmt = '{:,.0f}') # 레이블 형싱 지정
[Text(0, 0, '4,000'), Text(0, 0, '2,000'), Text(0, 0, '7,000')]

2023-06-19-barcolor_8_1

animal_names = ['Lion', 'Gazelle', 'Cheetah']
mph_speed = [50, 60, 75]

fig, ax = plt.subplots()
bar_container = ax.bar(animal_names, mph_speed)
ax.set(ylabel = 'speed in MPH', title = 'Running speeds', ylim = (0,80))
ax.bar_label(
    bar_container, fmt = lambda x: '{:.1f} km/h'.format(x * 1.61)
)
[Text(0, 0, '80.5 km/h'), Text(0, 0, '96.6 km/h'), Text(0, 0, '120.8 km/h')]

2023-06-19-barcolor_9_1

댓글남기기