2 분 소요

1. Stacked bar chart

import matplotlib.pyplot as plt
import numpy as np

# 펭귄 종류
species = (
    "Adelie\n $\\mu=$3700.66g",
    "Chinstrap\n $\\mu=$3733.09g",
    "Gentoo\n $\\mu=5076.02g$",
)

# 두 그룹에 속하는 펭귄 수
weight_counts = {
    "Below": np.array([70, 31, 58]),
    "Above": np.array([82, 37, 66])
}

width = 0.5 # 막대 그래프 너비

fig, ax = plt.subplots()
bottom = np.zeros(3) # 막대 그래프의 아래쪽 위치

for boolean, weight_count in weight_counts.items():
    p = ax.bar(species, weight_count, width, label = boolean, bottom = bottom)
    bottom += weight_count

ax.set_title("Number of penguins with above average body mass")
ax.legend(loc = "upper right") # 범례 오른쪽 상단

plt.show()

2023-06-20-stackbar_1_0

2. Grouped bar chart with labels

import matplotlib.pyplot as plt
import numpy as np

# 펭귄 종류
species = ("Adelie", "Chinstrap", "Gentoo")

# 펭귄 속성과 측정값 딕셔너리
penguin_means = {
    'Bill Depth': (18.35, 18.43, 14.98),
    'Bill Length': (38.79, 48.83, 47.50),
    'Flipper Length': (189.95, 195.82, 217.19),
}

x = np.arange(len(species)) # 종류 수에 맞게 x축 위치
width = 0.25 # 막대 그래프 너비
multiplier = 0 # 막대 그래프 위치 조정하기 위한 변수

fig, ax = plt.subplots(layout = 'constrained') # constrained: 축의 크기 자동 조정

for attribute, measurement in penguin_means.items():
    offset = width * multiplier # 막대 그래프의 위치
    rects = ax.bar(x + offset, measurement, width, label = attribute)
    ax.bar_label(rects, padding = 3) # padding: 값과 막대 사이의 여백
    multiplier += 1

ax.set_ylabel('Length (mm)')
ax.set_title('Penguin attributes by species')
ax.set_xticks(x + width, species)
ax.legend(loc = 'upper left', ncols = 3) # 범례 열 수: 3
ax.set_ylim(0, 250)

plt.show()

2023-06-20-stackbar_3_0

3. Horizontal bar chart

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(19680801)

plt.rcdefaults() # matplotlib 기본 설정 복원
fig, ax = plt.subplots()

people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people)) # y축 위치
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people)) # 무작위 난수 값

ax.barh(y_pos, performance, xerr = error, align = 'center')
ax.set_yticks(y_pos, labels = people)
ax.invert_yaxis() # y축 상하 반전
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

plt.show()

2023-06-20-stackbar_5_0

4. Broken Barh

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.broken_barh([(110, 30), (150, 10)], (10, 9), facecolors = 'tab:blue') # 끊어진 수평 막대 (시작위치, 너비)
ax.broken_barh([(10, 50), (100, 20), (130, 10)], (20, 9),
               facecolors = ('tab:orange', 'tab:green', 'tab:red')) # facecolos: 막대 그래프 색상
ax.set_ylim(5, 35)
ax.set_xlim(0, 200)
ax.set_xlabel('seconds since start')
ax.set_yticks([15, 25], labels = ['Bill', 'Jim']) # y축 눈금 위치
ax.grid(True) # 그리드 표시
ax.annotate('race interrupted', (61, 25), # 주석 추가
            xytext = (0.8, 0.9), textcoords = 'axes fraction', # xytext: 텍스트가 표시될 위치, textcoords: 좌표 시스템
            arrowprops = dict(facecolor = 'black', shrink = 0.05), # 화살표의 스타일
            fontsize = 16,
            horizontalalignment = 'right', verticalalignment = 'top') # hor~: 가로 정렬, ver~: 세로 정렬

plt.show()

2023-06-20-stackbar_7_0

broken_barh 그래프는 주로 시간 또는 구간에 따른 데이터를 시각화하는 데 사용됩니다. 이 그래프는 끊어진 수평 막대로 표현되며, 각 막대는 특정 구간 또는 시간 동안의 데이터를 나타냅니다. 보통 다음과 같은 상황에서 사용될 수 있습니다.

  • 일정 구간의 데이터 표현
  • 비교 및 차이 시각화
  • 상황 변화 시각화
  • 작업 일정 표현

5. CapStyle

import matplotlib.pyplot as plt
from matplotlib._enums import CapStyle

CapStyle.demo() # 선 끝 모양에 대한 데모 실행, 다양한 선 끝 모양 예시
plt.show()
C:\Users\82104\AppData\Local\Temp\ipykernel_19152\3317644853.py:4: UserWarning: Matplotlib is currently using module://matplotlib_inline.backend_inline, which is a non-GUI backend, so cannot show the figure.
  CapStyle.demo()

2023-06-20-stackbar_10_1

CapStyle은 matplotlib에서 선의 끝 모양을 지정하는 데 사용되는 열거형입니다. 선은 일반적으로 시작점과 끝점이 있으며, 이 끝점의 모양을 지정함으로써 시각적인 효과를 부여할 수 있습니다. CapStyle은 선의 끝점 모양을 지정하는 옵션을 제공하여 그래프의 모양을 더욱 다채롭게 만들 수 있습니다.

댓글남기기