일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- python
- 머신러닝
- pandas filter
- maplotlib
- matplotlib
- 리스트
- Slicing
- INSERT
- plt
- SQL
- MacOS
- Folium
- 자료구조
- barh
- pandas 메소드
- 등비수열
- DataFrame
- numpy
- 기계학습
- Machine Learning
- 재귀함수
- 순열
- 파이썬
- 문제풀이
- 조합
- tree.fit
- 등차수열
- 통계학
- pandas
- 스터디노트
Archives
- Today
- Total
코딩하는 타코야끼
[Matplotlib] 2강_각종 그래프 그리기_(Line Plot) 본문
728x90
반응형
1. 선 그래프 (Line plot) 그리기
📍 선 그래프(꺽은선 그래프)
- 점과 점을 선으로 연결한 그래프
- 시간의 흐름에 따른 변화를 표현할 때 많이 사용한다. (시계열)
- plot([x], y)
- 1번인수 : x값(생략가능), 2번인수 y값
- 인수가 하나인 경우 y 축의 값으로 설정되고 X값은 (0 ~ len(y)-1) 범위로 지정된다.
- x,y 의 인수는 리스트 형태의 객체들을 넣는다.
- 리스트
- 튜플
- numpy 배열 (ndarray)
- 판다스 Series
- x와 y의 size는 같아야 한다.
- 하나의 axes(subplot)에 여러 개의 선 그리기
- 같은 axes에 plot()를 여러번 실행한다.
📍 선 스타일
x = np.linspace(1, 10, num=100) # 1 ~ 10을 100등분(num) 한 분위값으로 이뤄진 1차원 배열을 생성.
x2 = pd.Series(x)
# plt 함수를 이용해서 선 그래프 그리기.
plt.plot(x, x, marker = ".", c = "purple")
plt.plot(x,x+1, linestyle = "--")
plt.plot(x,x+2, linestyle = ':')
plt.plot(x,x+3, linestyle = "-.", linewidth = 5) # linewidth 는 라인강고 가능.
plt.show()
📍 선 그래프 활용¶
- 서울시 연도별 황사 경보발령 현황
- 연도별 관측일수와 황사최대농도의 변화를 그래프로 시각화
df = pd.read_csv('data/서울시 연도별 황사 경보발령 현황.csv')
df.shape
>>>
(12, 7)
df.info
>>>
<bound method DataFrame.info of 년도 주의보 발령횟수 주의보 발령일수 경보 발령횟수 경보 발령일수 관측일수 최대농도
0 2006 4 5 1 2 11 2941
1 2007 3 4 1 1 12 1355
2 2008 1 1 1 1 11 933
3 2009 2 3 2 3 9 1157
4 2010 4 5 2 3 15 1354
5 2011 4 7 0 0 9 662
6 2012 0 0 0 0 1 338
7 2013 0 0 0 0 3 226
8 2014 0 0 0 0 10 259
9 2015 1 2 1 2 15 902
10 2016 0 0 0 0 7 481
11 2017 0 0 0 0 10 423>
🌓 '최대농도(㎍/㎥/시)' => 최대농도
# 같은 코드
df.rename(columns = {'최대농도(㎍/㎥/시)':'최대농도'}, inplace = True)
df.rename(columns = {df.columns[-1]:'최대농도'},inplace = True)
🌓 년도에 따른 황사 최대 농도의 변화흐름
plt.figure(figsize = (10, 3))
plt.plot(df['년도'], df['최대농도'], marker = ".")
plt.title('서울시 년도별 황사 최대농도의 변화흐름')
plt.xlabel('년도', fontsize = 15)
plt.ylabel('최대농도', fontsize = 15)
plt.xticks(df["년도"],
labels=[str(y)+'년' for y in df['년도']], # tick 라벨의 size == ticks 의 size
rotation = 45
) # 눈근의 위치. labels = ticks 라벨에 사용할 문자열 리스트
plt.grid(True, linestyle=":")
plt.show()
🌓 년도에 따른 주의보/경보 발령횟수의 변화 ==> 하나의 subplot 에 같이 그리기.
plt.figure(figsize = (10,3))
plt.plot(df['년도'], df['주의보 발령횟수'], alpha = 0.7, label = '주의보 발령횟수') # alpha 는 투명도 : 0(투명) ~ 1(불투명)
plt.plot(df['년도'], df['경보 발령횟수'], alpha = 0.5, label = '경보 발령횟수')
plt.title('년도별 주의보/경보 발령횟수')
plt.xlabel('년도')
plt.ylabel('횟수')
plt.legend()
plt.grid(True, linestyle = '--')
plt.show()
📍 최대 농도와 관측일 수의 연도별 변화를 시각화
- 하나의 축을 공유하고 두개의 축을 가지는 그래프 그리기¶
- 값의 범위(Scale)이 다른 두 값과 관련된 그래프를 한 Axes(subplot)에 그리는 경우
- X축을 공유해 2개의 Y축을 가지는 그래프
- axes.twinx() 를 이용해 axes를 복사
- Y축을 공유해 2개의 X축을 가지는 그래프
- axes.twiny() 를 이용해 axes를 복사
🌓 년도별 관측일수와 최대농도의 변화르흠을 하나의 axes에 그리기.
plt.figure(figsize = (10,5))
plt.plot(df['년도'],df['관측일수'], label = '관측일수', marker = '.')
plt.plot(df['년도'],df['최대농도'], label = '최대농도', marker = ".")
plt.title('년도별 관측일수와 최대농도의 변화흐름')
plt.xlabel('년도')
plt.ylabel('최대농도 / 관측일수')
plt.legend()
plt.grid(True, linestyle = ':')
plt.show()
df[['관측일수','최대농도']].agg(['min','max'])
🌓 twinx()를 이용해서 x축은 같이 사용하고 ysms 따로 사용하도록 처리.
plt.figure(figsize = (15,5))
ax1 = plt.gca() # 관측일수
ax2 = ax1.twinx() # ax1과 x축을 공유하는 새로운 subplot을 생성.
ax1.plot(df['년도'], df['관측일수'], label = '관측일수', color = 'red', marker = ".")
ax2.plot(df['년도'], df['최대농도'], label = '최대농도', c = 'g', marker = '.')
ax1.set_title('년도에 따른 관측일수, 최대농도의 변화')
ax1.set_xlabel('년도')
ax1.set_ylabel('관측일수')
ax2.set_ylabel("최대농도")
ax1.legend(loc = 'upper left', bbox_to_anchor = (1.05, 1))
ax2.legend(loc = 'upper left', bbox_to_anchor = (1.05, 0.93))
plt.grid(True, linestyle = "--")
plt.show(
🌓 legend 위치 지정
- 미리 지정된 위치로 잡기.
- legend(loc="상하위치 좌우위치")
- 상하: upper, center, lower, 좌우: left, center, right
- 정가운데 : 'center', 'best' : 최적의 위치를 알아서 잡아준다.(default)
- legend(bbox_to_anchor=(x,y), loc = 'box의 상하, 좌우 위치')
- bbox_to_anchor
- 전체 subplot의 x축과 y축의 비율
- legend(loc="상하위치 좌우위치")
- loc -> bbox_to_anchor 좌표지점에 범례 box의 어느 지점을 붙일 것인지 지정.
- ex) bbox_to_anchor = (1,1), loc = 'upper left' : subplot의 (1,1)지점의 범례박스의 위/왼쪽 점을 맞춘다.
- 0 ~ 1 사이는 박스 안쪽, 1 이상이면 박스 바깥쪽.
x = [1, 2 ,3]
y = np.array([10,20,30])
plt.plot(x, y, label = 'plot1')
plt.plot(x, y+1, label = 'plot2')
plt.plot(x, y+2, label = 'plot3')
plt.plot(x, y+3, label = 'plot4')
plt.plot(x, y+4, label = 'plot5')
plt.plot(x, y+5, label = 'plot6')
plt.plot(x, y+6, label = 'plot7')
plt.plot(x, y+7, label = 'plot8')
plt.plot(x, y+8, label = 'plot9')
plt.plot(x, y+9, label = 'plot10')
plt.legend(bbox_to_anchor = (1,1), loc = 'upper left',
ncol = 2, shadow = True) # ncol은 줄 나누기, shadow는 그림자 주기
plt.show()
반응형
'[T.I.L] : Today I Learned > Matplotlib' 카테고리의 다른 글
[Matplotlib] 4강_Pandas 시각화 (0) | 2023.05.11 |
---|---|
[Matplotlib] 3강_각종 그래프 그리기_( pie( ), hist( ), boxplot( ) ) (0) | 2023.05.11 |
[Matplotlib] 2강_각종 그래프 그리기_(Scatter Plot / Bar plot) (0) | 2023.05.09 |
[Matplotlib] 1강_Matplotlib 개요 (0) | 2023.05.09 |
[Matplotlib] 한글처리 및 환경설정 (0) | 2023.05.09 |