
데이터 분석을 위한 Python
✔️ Matplotlib 그래프 생성 및 세부 설정
✔️ Matplotlib 그래프 세부 설정
라인 그래프
set_linestyle(모양)
선 모양 바꾸기
+ 모양 종류
'-' : 실선 (solid)
'--' : 대쉬(dashed)
'-.' : 대시-닷(dash‑dot)
':' : 점선 (dotted)
',' : 픽셀 점 (pixel)
# 4개의 랜덤한 데이터 생성(100개의 난수 생성)
data1, data2, data3, data4 = np.random.randn(4, 100)
# 그래프 그릴 공간 설정
fig, ax = plt.subplots(figsize=(6,3.3))
# x축 값 생성(data1의 길이만큼 0부터 순차 입력)
x = np.arange(len(data1))
# x축에 x, data1의 누적합/data2의 누적합 그래프 생성
ax.plot(x, np.cumsum(data1), color='blue', linewidth=3, linestyle='-')
ax.plot(x, np.cumsum(data2), color='orange', linewidth=3, linestyle='--')
# 그래프 출력
plt.show()

+
눈금자 단위 구간 설정
# xdata에 값 생성(data1의 길이만큼 0부터 순차 입력)
xdata = np.arange(len(data1))
# 그래프 그릴 공간 설정
fig, ax = plt.subplots(2,1, figsize=(7, 3.7), layout='constrained')
# 자동 눈금 설정된 라인 그래프 생성
ax[0].plot(xdata, data1)
ax[0].set_title('Automatic ticks')
# 수동 눈금 설정된 라인 그래프 생성
ax[1].plot(xdata, data1)
# X축 눈금을 0, 30, 60, 90 위치에 'zero', '30', 'sixty', '90'로 지정
ax[1].set_xticks(np.arange(0, 100, 30), ['zero', '30', 'sixty', '90'])
# Y축 눈금을 -1.5, 0, 1.5 위치만 표시
# 그래프 제목 설정
ax[1].set_yticks([-1.5, 0, 1.5])
ax[1].set_title('Manual ticks')
# 그래프 출력
plt.show()

산점도 그래프
산점도 그래프 생성 및 색 변경
facecolor(안쪽색)
engecolor(테두리색)
컬러를 RGB 값으로 주고 싶으면 (0, 1, 0.5) 와 같이 0-1사이의 숫자를 R, G, B 순서의 튜플로 전달
# 그래프 그릴 공간 설정
fig, ax = plt.subplots(figsize=(6,3.3))
# 산점도 그래프 생성
# X좌표(data1), Y좌표(data2)
# 마커 크기(50), 마커 내부 색상(C0), 마커 테두리 색상(k)
ax.scatter(data1, data2, s=50, facecolor='C0', edgecolor='k')
# 그래프 출력
plt.show()

# 그래프 그릴 공간 설정
fig, ax = plt.subplots(figsize=(6,3.3))
# 산점도 그래프 생성
# X좌표(data3), Y좌표(data4)
# 마커 크기(50), 마커 내부 색상((0,1,0.5)), 마커 테두리 색상(C15)
ax.scatter(data3, data4, s=50, facecolor=(0,1,0.5), edgecolor='C15')
# 그래프 출력
plt.show()

+
산점도 그래프의 마커 모양 지정
마커 종류 확인
`.` : point marker
`,` : pixel marker
`o` : circle marker
`v` : triangle_down marker
`^` : triangle_up marker
`<` : triangle_left marker
`>` : triangle_right marker
`1` : tri_down marker
`2` : tri_up marker
`3` : tri_left marker
`4` : tri_right marker
`8` : octagon marker
`s` : square marker
`p` : pentagon marker
`P` : plus (filled) marker
`*` : star marker
`h` : hexagon1 marker
`H` : hexagon2 marker
`+` : plus marker
`x` : x marker
`X` : x (filled) marker
`D` : diamond marker
`d` : thin_diamond marker
`\|` : vline marker
`_` : hline marker
# 그래프 그릴 공간 설정
fig, ax = plt.subplots(figsize=(6,3.3))
# data1,2,3,4 데이터 마커의 모양만 다르게 입력된 산점도 그래프 생성
ax.plot(data1, '8', label='data1')
ax.plot(data2, '2', label='data2')
ax.plot(data3, 'p', label='data3')
ax.plot(data4, 's', label='data4')
# 그래프 출력
plt.show()

히스토그램 그래프
히스토그램 그래프 생성
X축, Y축 이름, 눈금, 그래프 이름 설정 가능
# 정규분포와 표준편차 설정
# 10000개의 난수 생성(평균이 115, 표준편차가 15인 정규분포)
mu, sigma = 115,15
x = mu + sigma * np.random.randn(10000)
# 그래프 그릴 공간 설정
fig, ax = plt.subplots(figsize=(7, 3.7))
# x 입력, 구간수(50), 확률 밀도 함수 형태로 정규화 진행 설정
# 막대 내부 색상(blue), 투명도(0.75) 설정
n, bins, pathches = ax.hist(x, 50, density=True, facecolor='blue', alpha=0.75)
# x축, y축 설명 및 그래프 제목 설정
ax.set_xlabel('Length [cm]')
ax.set_ylabel('Probability')
ax.set_title('Ardvark lengths\n (not really)')
# 그래프 내부에 텍스트 추가
ax.text(65, .025, r'$\mu=115, \ \sigma=15$')
# x,y 축의 범위 설정
ax.axis([60, 170, 0, 0.03])
# ax.axis('off') # 그래프만 보이게 만들어줌
# 그래프 출력
plt.show()

카테고리 막대 그래프
# 그래프 그릴 공간 설정
fig, ax = plt.subplots(figsize=(7, 3.7))
# x축에 나타낼 카테고리 값 및 막대 색상 지정
categories = ['turnips', 'rutabaga', 'cucumber', 'pumpkins']
colors = ['#FF6F61', '#6B5B95', '#88B04B', '#FFA500']
# 카테고리를 적용한 막대 그래프 생성
ax.bar(categories, np.random.rand(len(categories)), color=colors)
# 그래프 출력
plt.show()

이번 내용에서는 파이썬 Matplotlib를 활용한 라인/산점도/히스토그램/막대 그래프 생성에 대해 알아보았습니다.
데이터 분석을 하기 위해서는 가장 꾸준히 공부해야 하는 언어는 파이썬(Python)이라고 생각합니다.
앞으로 꾸준히 파이썬(Python) 내용을 공부하고 정리할테니 파이썬 코딩에 도움이 되었으면 좋겠습니다.
데이터 분석과 관련된 다양한 정보들이 확인하고 싶다면
관심 있는 분들은 방문해서 좋은 정보 얻어가시길 바랍니다.
ECODATALIST
데이터 분석 공부 열심히 하는 중😁
everyonelove.tistory.com
반응형
'Python > 데이터 분석을 위한 Python' 카테고리의 다른 글
| [Python] 파이썬_중앙값과 최빈값을 활용한 결측치 대체 및 scikit-learn 활용 결측치 대체 (0) | 2025.04.24 |
|---|---|
| [Python] 파이썬_데이터 분석 과정의 결측치 처리 (0) | 2025.04.22 |
| [Python] 파이썬_파이썬 Matplotlib를 활용한 그래프 생성 (0) | 2025.04.21 |
| [Python] 파이썬_파이썬의 데이터프레임 합치기와 중복된 행 제거 (0) | 2025.04.21 |
| [Python] 파이썬_파이썬의 Pandas 기능 활용(2) (0) | 2025.04.17 |