Mac 환경에서 Spotfire 다뤄보기

|

Matplotlib subplots 사용해보기

|

개인공부 후 자료를 남기기 위한 목적임으로 내용 상에 오류가 있을 수 있습니다.


Matplotlib

import matplotlib.pyplot as plt

파이차트와 바 차트 조합해보기

# 실제 판매량 데이터 (단위: 만대)
actual_sales = [350, 250, 150, 100, 150]
fig, (ax1, ax2) = plt.subplots(1,2,  # (1,2) > 1x2
                               figsize=(10,4))

# 왼쪽에 파이차트
ax1.pie(market_share, labels=brands, 
        colors=colors,  
        autopct='%.1f%%')

ax1.set_title('시장점유율')

# 오른쪽에 바차트
ax2.bar(brands, market_share,
        color=colors
        )
ax2.set_title('시장점유율')


plt.show()

서브플롯으로 여러 파이차트 비교해보기

# 분기별 데이터
q1_data = [35, 25, 15, 10, 15]
q2_data = [33, 27, 16, 12, 12]
q3_data = [30, 30, 18, 15, 7]
q4_data = [28, 32, 20, 15, 5]
colors = ['#ffd6ee','#fff0f1','#ecd2e0','#ced1f8','#a7abde']
color2 = ['#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231']
fig, axes = plt.subplots(2,2,  # (2x2) > 총 4개 구현한다는 의미 
                         figsize=(8,7)
                         )
# print(fig)
# print(axes)

axes[0,0].pie(q1_data, labels=brands, colors=colors, autopct='%.1f%%')
axes[0,0].set_title('1분기')
axes[0,1].pie(q2_data, labels=brands, colors=color2, autopct='%.1f%%')
axes[0,1].set_title('2분기')
axes[1,0].pie(q3_data, labels=brands, colors=colors, autopct='%.1f%%')
axes[1,0].set_title('3분기')
axes[1,1].pie(q4_data, labels=brands, colors=colors, autopct='%.1f%%')
axes[1,1].set_title('4분기')

plt.tight_layout()  # 서브플롯 간격 조절
plt.show()

Matplotlib 사용해보기(파이차트 pie, 도넛차트)

|

개인공부 후 자료를 남기기 위한 목적임으로 내용 상에 오류가 있을 수 있습니다.


Matplotlib

import matplotlib.pyplot as plt

기본 데이터는 아래와 같다.

# 브랜드별 시장점유율 데이터
brands = ['삼성', '애플', 'LG', '샤오미', '기타']
market_share = [35, 25, 15, 10, 15]

pie

  • 여러 시각화중에 넣을 수 있는 정보가 제한적
  • 하나의 컬럼안에 범주형 정보를 비율로 표현
  • 전체합이 100%
  • 범주 갯수가 5개 이상이면, 권장되지 않는다(가독성이 떨어짐)
  • 많은 컬럼들을 비율로 나타낼때, 100% 바 차트를 고려
# 파이차트 기본 시각화 
plt.figure(figsize=(4,4))
# autopct='%.1f%%'
# %: 뒤에 문자들이 포매팅 규칙이 오게된다(시작점의미)
# 1.1f  실제 숫자를 어떻게 표현할지 , '.1'소수점 1자리까지 표현을 의미 | f 는 부동소수점 처리
# %%: %를 출력하라는 의미
plt.pie(market_share, labels=brands, autopct='%.1f%%')
plt.show()

파이 색상 지정

# 파이차트 색상 지정 
colors=['#ff9999','#66b3ff','#99ff99','#ffcc99','#c2c2f0']

plt.figure(figsize=(4,4))
plt.pie(market_share, labels=brands, 
        colors=colors,   # 색상지정 
        autopct='%.1f%%',  # 숫자의 소수점 지정
        shadow=True,  # 그림자
        startangle=90,  # 시작각도
        explode=[0.2,0.1,0.1,0.1,0]  # 분리된 파이차트 > 강조하고 싶으면 0보다 크게, 아니면 0 / 0.~ 이런식으로 간격 조절 가능 
        )

plt.show()

범례 및 레전드 추가

colors=['#ff9999','#66b3ff','#99ff99','#ffcc99','#c2c2f0']

plt.figure(figsize=(4,4))
plt.pie(market_share, labels=brands, 
        colors=colors,  
        autopct='%.1f%%',  
        shadow=True, 
        startangle=90,  
        explode=[0.2,0.1,0.1,0.1,0]  
        )
 
# 범례추가
# bbox_to_anchor=(1,0.5) > 범례박스가 bbox/레전드 위치 조절 (가로축, 세로축)
plt.legend(brands, loc='center left',  bbox_to_anchor=(1.1,0.5))  
plt.show()

도넛차트

plt.figure(figsize=(4,4))

# wedges: 도넛 조각을 의미하는 객체리스트
# texts: 각조각의 라벨
# autotexts: 각 조각 내부숫자(비율)을 의미 
wedges, texts, autotexts = plt.pie(
    market_share, labels=brands,
    colors=colors,
    autopct='%.1f%%',
    wedgeprops={'width':0.5}  # 도넛 두께 설정 > 보통 0~1사이 값 넣음 
)

print(wedges)  # 도넛 객체들 
print(texts)  # 좌표, 브랜드 이름
print(autotexts)  # 좌표, 퍼센트


plt.title('스마트폰 시장 점유율', fontsize=20)

plt.show()

도넛 차트의 레이블과 퍼센트 분리

plt.figure(figsize=(4,4))

wedges, texts, autotexts = plt.pie(
    market_share, labels=brands,
    colors=colors,
    autopct='%.1f%%',
    wedgeprops={'width':0.5},
    pctdistance=0.73  # 안쪽 퍼센트 거리조절 
)

# 퍼센트 친구들 설정해주기 
for autotext in autotexts:
    autotext.set_color('purple')
    autotext.set_fontsize(12)
    autotext.set_fontweight('bold')

for text in texts:
    text.set_color('y')
    text.set_fontsize(12)
    text.set_fontweight('bold')


plt.title('스마트폰 시장 점유율', fontsize=20)

plt.show()

도넛 중간 총 텍스트 삽입

plt.figure(figsize=(4,4))

wedges, texts, autotexts = plt.pie(
    market_share, labels=brands,
    colors=colors,
    autopct='%.1f%%',
    wedgeprops={'width':0.5},
    pctdistance=0.73 
)

for autotext in autotexts:
    autotext.set_color('purple')
    autotext.set_fontsize(12)
    autotext.set_fontweight('bold')

for text in texts:
    text.set_color('y')
    text.set_fontsize(12)
    text.set_fontweight('bold')

# 중앙에 총 판매량 표시 
total_sales = sum(market_share)
plt.text(0,0,  # (x,y)
         f'{total_sales}%',
         horizontalalignment='center',  # 가로축을 센터에 맞춰주고
         verticalalignment='center',  # 세로축을 센터에 맞춰줌 
         fontsize=20,
         fontweight='bold'
         )


plt.title('스마트폰 시장 점유율', fontsize=20)

plt.show()

Matplotlib subplot과 subplots의 차이

|

Matplotlib 사용해보기(히스토그램 hist)

|

개인공부 후 자료를 남기기 위한 목적임으로 내용 상에 오류가 있을 수 있습니다.


Matplotlib

import matplotlib.pyplot as plt

hist 히스토그램

  • 바 차트와 비슷
    • 차이점: 가로축에 수치형 데이터가 들어감 (바차트는 범주형이었음)
# 시험 점수 데이터 (100명) 생성
np.random.seed(42)
scores = np.random.normal(75, 15, 100)  # 평균 75점, 표준편차 15
scores = np.clip(scores, 0, 100)  # 0-100점 범위로 제한 / clip> 제한하는 함수
# 히스토그램 구현
plt.figure(figsize=(5,3))
# bins: 데이터를 구획하는 숫자 > 데이터를 몇 구획으로 나눌것인가
# 많이할수록 더욱 세분화되어 보임
plt.hist(scores, bins=10,
         color='red',
         alpha=0.5,
         edgecolor='red',
         linewidth=1,
        #  density=True
         )
plt.title('시험 점수 분포')
plt.xlabel('점수')
plt.ylabel('학생수')
plt.show()

통계선 추가해보기

통계션을 추가해서 많이 사용 > 평균, 중앙값 > .axvline(값)

plt.figure(figsize=(5,3))
plt.hist(scores, bins=10,
         color='red',
         alpha=0.5,
         edgecolor='red',
         linewidth=1
         )

mean_score = np.mean(scores)
median_score = np.median(scores)

# .axvline > x축 통계선 추가 
plt.axvline(mean_score, color='purple', linestyle='--', label=f'평균: {mean_score:.2f}점')
plt.axvline(median_score, color='black', linestyle=':', label=f'중앙값: {median_score:.2f}점')
plt.legend(fontsize=8, loc='upper left')

plt.title('시험 점수 분포')
plt.xlabel('점수')
plt.ylabel('학생수')
plt.show()

밀도 히스토그램

  • y축이 카운트 > 히스토그램
  • x축이 비율 > 밀도 히스토그램
- 두개의 시각화 표현
- 밀도 히스토그램 구현(density=True)
plt.figure(figsize=(6,4))

plt.subplot(1,2,1)
plt.hist(scores, bins=10,
         color='red',
         alpha=0.5,
         edgecolor='red',
         linewidth=1,
        #  density=True
         )
plt.title('시험 점수 분포')
plt.xlabel('점수')
plt.ylabel('학생수')

plt.subplot(1,2,2)
plt.hist(scores, bins=10,
         color='red',
         alpha=0.5,
         edgecolor='red',
         linewidth=1,
         density=True  # 밀도 히스토그램이 표현됨
         )
plt.title('시험 점수 분포')
plt.xlabel('점수')
plt.ylabel('학생수')


plt.show()