막대그래프(과목별 점수 데이터)
리스트 데이터 - subject(과목)을 x축으로, score(점수)를 y축으로 한 과목별 점수를 시각화
그래프 : 막대그래프
사용모듈 : matplotlib.pyplot
import matplotlib.pyplot as plt
subject=["Oracle", "Python","Sklearn","Tensorflow"] #x축의 값
score=[65,90,85,95] #y축의 값
plt.style.use("ggplot")
fig=plt.figure(figsize=(15,10)) #그래프 작성 창(창크기설정)
ax1=fig.add_subplot(1,1,1) #1행1열1번째
ax1.bar(range(len(subject)), score, align="center", color="darkblue")
# ax1.bar : 막대그래프 # range(len(subjects)) : x축에 표시될 내용
# score : y축 # align="center" : 정렬 # color : 막대색깔
plt.xticks(range(len(subject)),subject,rotation=0,fontsize="small") # x축의 값들 설정
plt.xlabel("Subject") # x축 라벨 이름
plt.ylabel("Score") # y축 라벨 이름
plt.title("Class Score") # 그래프 제목
plt.savefig("graph/score.png", dpi=400,bbox_inches="tight") # graph폴더에 score.png 파일로 저장
연합막대그래프(북한전력량 데이터)
엑셀 데이터 - 남북한발전전력량.xlsx파일에서 1990~2016년 북한전력량(수력,화력, 전년대비증감율)을 시각화
그래프 : 연합막대그래프
그래프 사용모듈 : matplotlib.pyplot
import pandas as pd
import matplotlib.pyplot as plt
### 필요한 데이터 추출
# 엑셀 판다스로 읽기
df = pd.read_excel("../data/남북한발전전력량.xlsx")
df
# 북한 발전 전력량만 조회
df = df.loc[5:]
df
# 전력량 (억㎾h) 컬럼삭제
del df["전력량 (억㎾h)"]
df
# 발전 전력별 컬럼 인덱스로 변경
df.set_index("발전 전력별", inplace=True)
df
#전치행렬로 변경
df=df.T
df
# 컬럼명 변경 : "합계" => "총발전량"
df=df.rename(columns={"합계":"총발전량"})
df
# "총발전량 - 1년" 컬럼 추가 / 값 - 전년도총발전량
df["총발전량-1년"] = df["총발전량"].shift(1) # shift(1) : 총발전량 컬럼 앞 레코드의 데이터
df
# "증감율" 컬럼 추가 / 값 - ((총발전량/총발전량-1년)-1)*100
df['증감율'] = ((df['총발전량']/df['총발전량-1년'])-1)*100
df
### 그래프
plt.style.use("ggplot") # 그래프 스타일 서식 지정
plt.rcParams['axes.unicode_minus']=False # 마이너스 부호 출력
plt.rc('font', family="Malgun Gothic") # 폰트 맑은고딕 설정
# 연합막대그래프 : 수력, 화력 1개의 막대그래프로 표시(stacked=True 두개의 그래프 쌓아서 출력)
ax1 = df[['수력','화력']].plot(kind='bar', figsize=(20,10),width=0.7, stacked=True)
ax2 = ax1.twinx() #ax1 그래프 영역 복사 ax2 그래프 영역으로 사용
ax2.plot(df.index, df.증감율, ls='--', marker='o', markersize=20,
color='green',label='전년대비 증감율(%)') # ls='--' : 선의 종류. 점선
ax1.set_ylim(0,500)
ax2.set_ylim(-50,50)
ax1.set_xlabel('연도', size=20)
ax1.set_ylabel('발전량 (억kWh)')
ax2.set_ylabel('전년 대비 증감률(%)')
plt.title('북한 전력 발전량(1990~2016)',size=30)
ax1.legend(loc='upper left') #범례 위치 지정
ax2.legend(loc='upper right')
plt.savefig("graph/북한전력량.png",dpi=400,bbox_inches="tight")
plt.show()
히스토그램(seaborn모듈 mpg 데이터셋)
seaborn모듈 mpg 데이터의 mpg컬럼 - 자동차 연비 데이터 시각화
그래프 : 히스토그램(값의 구간별 건수/밀도 출력. 값의 분포를 알 수 있다.)
그래프 사용모듈 : pandas, matplotlib.pyplot
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
### 필요한 데이터 추출
# seaborn모듈 mpg(자동차 연비 데이터)데이터 판다스로 읽기
df = sns.load_dataset("mpg")
df.info()
### pandas모듈 : DataFrame.plot() 함수로 그래프 작성
plt.style.use("classic") # 그래프 스타일 서식 지정
df["mpg"].plot(kind="hist", bins=20, color='coral', figsize=(10,5))
# kind="hist" : 히스토그램 # bins=20:값의 구간 20개로 설정
plt.title("Histogram")
plt.xlabel('mpg')
plt.savefig("graph/mpg(pandas 히스토그램).png",dpi=400,bbox_inches="tight")
plt.show()
### matplotlib모듈 : 히스토그램 그래프 작성
plt.style.use("classic")
plt.hist(df["mpg"],bins=20) # bins : 값의 구간 지정. 기본 10
plt.title("Histogram")
plt.xlabel('mpg')
plt.savefig("graph/mpg(matplotlib 히스토그램).png",dpi=400,bbox_inches="tight")
plt.show()
산점도(seaborn모듈 mpg 데이터셋)
seaborn모듈 mpg 데이터의 weight컬럼, mpg컬럼 - 연비와 차중에 대한 데이터 시각화
그래프 : 산점도
그래프 사용모듈 : pandas, matplotlib.pyplot
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
### 필요한 데이터 추출
# seaborn모듈 mpg(자동차 연비 데이터)데이터 판다스로 읽기
df = sns.load_dataset("mpg")
df.info()
### pandas모듈 : DataFrame.plot() 함수로 그래프 작성
plt.style.use("ggplot")
df.plot(kind='scatter', x='weight', y='mpg', c='coral', s=40, figsize=(10, 5))
# kind="scatter" : 산점도 # c=색깔 # s=점의크기
plt.savefig("graph/mpg_weight(pandas 산점도).png",dpi=400,bbox_inches="tight")
plt.show()
### matplotlib모듈 : 산점도 그래프 작성
plt.style.use("classic")
plt.figure(figsize=(10, 5))
plt.scatter(df["weight"], df["mpg"], c='coral', s=20 )
plt.savefig("graph/mpg_weight(matplotlib 산점도).png",dpi=400,bbox_inches="tight")
plt.show()
버블그래프(seaborn모듈 mpg 데이터셋)
seaborn모듈 mpg 데이터의 weight컬럼, mpg컬럼 cylinders컬럼 - 3개의 데이터 산점도로 데이터 시각화
그래프 : 버블그래프(값의 최대값의 비율로 계산해서 점의 크기 및 색상 차별 데이터 생성)
그래프 사용모듈 : pandas
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
### 필요한 데이터 추출
# seaborn모듈 mpg(자동차 연비 데이터)데이터 판다스로 읽기
df = sns.load_dataset("mpg")
df.info()
# cyclinders 개수의 상대적 비율을 계산해서 시리즈 객체 생성
df["cylinders"].value_counts() #cylinders의 컬럼값별 갯수
cylinders_size = df.cylinders / df.cylinders.max() * 300
type(cylinders_size)
cylinders_size.value_counts()
### pandas모듈 : DataFrame.plot() 함수로 그래프 작성
'''
점의 크기를 테이터의 값으로 설정하기
3개의 변수 지정 : x축(weight데이터), y축(mpg데이터), 점의 크기(cylinders)
cyclinders : cylinders 컬럼 값을 최대값의 비율로 계산해서 데이터 생성
'''
df.plot(kind='scatter', x='weight', y='mpg', c='coral',\
s=cylinders_size,figsize=(10, 5),alpha=0.7) #alpha=0.7 : 투명도
plt.title("Scatter plot:mpg-weight-cylinders")
plt.savefig("graph/mpg_weight_cylinders(size 버블).png",dpi=400,bbox_inches="tight")
plt.show()
'''
점의 색상으로 테이터의 값을 설정하기
3개의 변수 지정 : x축(weight데이터), y축(mpg데이터), 점의 색상(cylinders)
marker='+' : 산점도에 표시되는 모양을 설정
cmap='viridis' : 맵플롯에서 색상모임. 값의 따른 색상의 목록
'viridis', 'plasma', 'inferno', 'magma', 'cividis'
c=cylinders_size : 색상
'''
df.plot(kind='scatter', x='weight', y='mpg', marker='+',\
figsize=(10, 5), cmap='plasma', c=df["cylinders"], \
s=50, alpha=0.7)
plt.title('Scatter Plot: mpg-weight-cylinders')
plt.savefig("graph/mpg_weight_cylinders(color 버블).png",transparent=True) #투명그림으로 저장
plt.show()
파이그래프(seaborn모듈 mpg 데이터셋)
seaborn모듈 mpg 데이터의 orgin컬럼 - 국가별자동차 갯수 비율 데이터 시각화
그래프 : 파이그래프
그래프 사용모듈 : pandas
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
### 필요한 데이터 추출
# seaborn모듈 mpg(자동차 연비 데이터)데이터 판다스로 읽기
df = sns.load_dataset("mpg")
df.info()
# origin 컬럼 값별 갯수 시리즈 객체 생성
mpg_origin = df["origin"].value_counts()
mpg_origin
type(mpg_origin) #pandas.core.series.Series
### pandas모듈 : DataFrame.plot() 함수로 그래프 작성
'''
autopct="%.1f%%" : 비율표시
%.1f : 소숫점이하 1한자리 표시
%% : % 문자의미
startangle=10 : 파이조각의 시작 각도
'''
mpg_origin.plot(kind="pie",figsize=(7,5),autopct="%.1f%%",startangle=10,
colors=['chocolate','bisque','cadetblue'])
plt.title("Model Origin",size=20)
#plt.axis("equal")
#plt.axis("auto")
plt.axis("square")
plt.legend(labels=mpg_origin.index,loc="upper right")
plt.savefig("graph/mpg_origin(pandas 파이).png",dpi=400,bbox_inches="tight")
plt.show()
박스그래프 2개(seaborn모듈 mpg 데이터셋)
seaborn모듈 mpg 데이터의 orgin컬럼 - 국가별자동차 그룹화 하여 연비 데이터 시각화
그래프 : 수직박스그래프, 수평박스그래프
그래프 사용모듈 : matplotlib.pyplot
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
### 필요한 데이터 추출
# seaborn모듈 mpg(자동차 연비 데이터)데이터 판다스로 읽기
df = sns.load_dataset("mpg")
df.info()
# origin 컬럼을 그룹화 하기
df[df['origin']=='japan']['mpg']
mpg_origin = df.groupby("origin").sum()
mpg_origin
mpg_origin = df.groupby("origin").count()
mpg_origin
df.origin.value_counts()
### matplotlib모듈 : 박스 그래프 작성
'''
origin 컬럼으로 그룹화 하여 연비 데이터 그래프로 출력
vert=False : 수평박스그래프로 출력
'''
plt.rc("font", family="Malgun Gothic")
plt.style.use('seaborn-poster')
fig = plt.figure(figsize=(15, 5))
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
ax1.boxplot(x=[df[df['origin']=='usa']['mpg'],
df[df['origin']=='japan']['mpg'],
df[df['origin']=='europe']['mpg']],
labels=['USA', 'JAPAN','EU'])
ax2.boxplot(x=[df[df['origin']=='usa']['mpg'],
df[df['origin']=='japan']['mpg'],
df[df['origin']=='europe']['mpg']],
labels=['USA', 'JAPAN','EU'],vert=False) # 가로로 표시
ax1.set_title('제조국가별 연비 분포(수직 박스 플롯)')
ax2.set_title('제조국가별 연비 분포(수평 박스 플롯)')
plt.savefig("graph/제조국가별 연비 분포 박스 플롯.png",dpi=400,bbox_inches="tight")
plt.show()
선형회귀그래프 2개(seaborn모듈 titanic 데이터셋)
seaborn모듈 titanic 데이터의 age컬럼, fare컬럼 - 타이타닉호 나이, 요금 데이터 시각화
그래프 : 선형회귀그래프(산점도+선형회귀선), 선형회귀그래프(회귀선 표시 안함)
그래프 사용모듈 : seaborn
import seaborn as sns
import matplotlib.pyplot as plt
### 필요한 데이터 추출
# seaborn모듈 titanic(타이타닉호 데이터)데이터 데이터프레임 객체 생성
titanic = sns.load_dataset("titanic")
titanic.info()
### seaborn모듈 : 선형회귀그래프 - 산점도+선형회귀선
'''
regplot : 선형회귀그래프 : 산점도 + 선형회귀선 표시
회귀선 : 모든 점에서 가장 가까운 점들을 선으로 표시.
x='age' : x축의 값
y='fare' : y축의 값
fit_reg=False : 회귀선 표시 안함
'''
sns.set_style('darkgrid') #style 설정
fig = plt.figure(figsize=(15, 5))
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
sns.regplot(x='age', y='fare', data=titanic, ax=ax1)
sns.regplot(x='age', y='fare', data=titanic, ax=ax2, fit_reg=False)
plt.savefig("graph/타이타닉호 선형회귀그래프.png",dpi=400,bbox_inches="tight")
plt.show()
히스토그램 (seaborn모듈 titanic 데이터셋)
seaborn모듈 titanic 데이터의 fare컬럼 - 타이타닉호 요금 데이터 시각화
그래프 : 히스토그램(distplot), 히스토그램(kdeplot), 히스토그램(histplot)
그래프 사용모듈 : seaborn, matplotlib.pyplot
import seaborn as sns
import matplotlib.pyplot as plt
### 필요한 데이터 추출
# seaborn모듈 titanic(타이타닉호 데이터)데이터 데이터프레임 객체 생성
titanic = sns.load_dataset("titanic")
titanic.info()
### seaborn모듈 : 히스토그램
'''
distplot() : kde(밀도),hist(빈도수)
kdeplot() : kde(밀도)
histplot() :hist(빈도수)
sns.distplot(titanic['fare'],ax=ax1) # kde(밀도),hist(빈도수) 출력
sns.distplot(titanic['fare'],hist=False, ax=ax1) # kde(밀도))출력
sns.distplot(titanic['fare'],kde=False, ax=ax1) # hist(빈도수) 출력
'''
fig = plt.figure(figsize=(15, 5))
ax1 = fig.add_subplot(1, 3, 1)
ax2 = fig.add_subplot(1, 3, 2)
ax3 = fig.add_subplot(1, 3, 3)
sns.distplot(titanic['fare'], ax=ax1)
sns.kdeplot(x='fare',data=titanic, ax=ax2)
sns.histplot(x='fare',data=titanic,ax=ax3)
ax1.set_title('titanic fare - distplot')
ax2.set_title('titanic fare - kdeplot')
ax3.set_title('titanic fare - histplot')
plt.savefig("graph/타이타닉호 히스토그램(seaborn모듈).png",dpi=400,bbox_inches="tight")
plt.show()
### matplot모듈 이용 : 히스토그램
titanic['fare'].plot(kind='hist', bins=50, color='coral', figsize=(10, 10))
plt.title('Histogram')
plt.xlabel('fare')
plt.savefig("graph/타이타닉호 히스토그램(matplot모듈).png",dpi=400,bbox_inches="tight")
plt.show()
히트맵(seaborn모듈 titanic 데이터셋)
seaborn모듈 titanic 데이터의 sex컬럼, class컬럼 - 타이타닉호 성별, 클래스 데이터 시각화
그래프 : 히트맵(범주형 데이터의 수치를 색과 값으로 표시)
그래프 사용모듈 : seaborn
import seaborn as sns
import matplotlib.pyplot as plt
### 필요한 데이터 추출
# seaborn모듈 titanic(타이타닉호 데이터)데이터 데이터프레임 객체 생성
titanic = sns.load_dataset("titanic")
titanic.info()
'''
pivot_table : 2개의 범주형데이터를 행,열로 재구분
aggfunc='size' : 데이터의 갯수
'''
# 피벗테이블 만들기 : 타이타닉호 성별, 클래스 재구분
table = titanic.pivot_table(index=['sex'], columns=['class'], aggfunc='size')
table
# 성별 인원수 조회하기
titanic["sex"].value_counts()
titanic.groupby("sex").count()["survived"]
### seaborn모듈 : 히트맵
'''
table : 표시할 데이터
annot=True : 데이터값 표시
fmt='d' : 정수형 으로 데이터 출력
cmap='YlGnBu' : 컬러맵. 색상표.
cbar=False : 컬러바 표시안함
'''
sns.heatmap(table,annot=True,fmt='d',
cmap='YlGnBu',linewidth=.5,cbar=True)
plt.savefig("graph/타이타닉호 성별 클래스 히트맵(seaborn모듈).png",dpi=400,bbox_inches="tight")
plt.show()
막대그래프(seaborn모듈 titanic 데이터셋)
seaborn모듈 titanic 데이터의 sex컬럼, survived컬럼, class컬럼 - 타이타닉호 성별, 생존율, 클래스 데이터 시각화
그래프 : 막대그래프
그래프 사용모듈 : seaborn
import seaborn as sns
import matplotlib.pyplot as plt
### 필요한 데이터 추출
# seaborn모듈 titanic(타이타닉호 데이터)데이터 데이터프레임 객체 생성
titanic = sns.load_dataset("titanic")
titanic.info()
### seaborn모듈 : 막대그래프
fig = plt.figure(figsize=(15, 5))
ax1 = fig.add_subplot(1, 3, 1)
ax2 = fig.add_subplot(1, 3, 2)
ax3 = fig.add_subplot(1, 3, 3)
titanic.groupby("sex").survived.value_counts()
sns.barplot(x='sex', y='survived', data=titanic, ax=ax1)
# data=titanic : 데이터프레임 객체.
sns.barplot(x='sex', y='survived', hue='class', data=titanic, ax=ax2)
# hue='class' : titanic['class'] 별로 분리
sns.barplot(x='sex', y='survived', hue='class', dodge=False, data=titanic, ax=ax3)
#dodge=False : 누적 표시
ax1.set_title('titanic survived - sex')
ax2.set_title('titanic survived - sex/class')
ax3.set_title('titanic survived - sex/class(stacked)')
plt.savefig("graph/타이타닉호 생존(seaborn모듈).png",dpi=400,bbox_inches="tight")
plt.show()
막대그래프(건수출력)(seaborn모듈 titanic 데이터셋)
seaborn모듈 titanic 데이터의 who컬럼, class컬럼 - 타이타닉호 who별, class별 건수 데이터 시각화
그래프 : 막대그래프(건수출력)-countplot
그래프 사용모듈 : seaborn
import seaborn as sns
import matplotlib.pyplot as plt
### 필요한 데이터 추출
# seaborn모듈 titanic(타이타닉호 데이터)데이터 데이터프레임 객체 생성
titanic = sns.load_dataset("titanic")
titanic.info()
# class별, who별로 count값 출력하기
print(titanic["who"].head())
titanic["who"].unique()
titanic["class"].value_counts()
### seaborn모듈 : 막대그래프(건수출력)
'''
palette='Set1' : 설정된 색상표.
hue='who' : 그룹화
dodge=False : 누적데이터로 출력
'''
fig = plt.figure(figsize=(15, 5))
ax1 = fig.add_subplot(1, 3, 1)
ax2 = fig.add_subplot(1, 3, 2)
ax3 = fig.add_subplot(1, 3, 3)
sns.countplot(x='class',palette='Set1', data=titanic, ax=ax1)
sns.countplot(x='class', hue='who', palette='Set2', data=titanic, ax=ax2)
table = titanic.pivot_table(index=['class'], columns=['who'], aggfunc='size')
table
sns.countplot(x='class', hue='who', palette='Set3',dodge=False, data=titanic, ax=ax3)
ax1.set_title('titanic class')
ax2.set_title('titanic class - who')
ax3.set_title('titanic class - who(stacked)')
plt.savefig("graph/타이타닉호 who, class 건수(seaborn모듈).png",dpi=400,bbox_inches="tight")
plt.show()
산점도(seaborn모듈 titanic 데이터셋)
seaborn모듈 titanic 데이터의 age컬럼, class컬럼 - 타이타닉호 나이, 클래스 데이터 시각화
그래프 : 산점도
그래프 사용모듈 : seaborn
import seaborn as sns
import matplotlib.pyplot as plt
### 필요한 데이터 추출
# seaborn모듈 titanic(타이타닉호 데이터)데이터 데이터프레임 객체 생성
titanic = sns.load_dataset("titanic")
titanic.info()
### seaborn모듈 : 산점도
sns.set_style('whitegrid')
fig = plt.figure(figsize=(15, 5))
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
sns.stripplot(x="class", y="age",data=titanic, ax=ax1) # 이산형 변수의 분포 - 데이터 분산 미고려
sns.swarmplot(x="class", y="age",data=titanic, ax=ax2) # 이산형 변수의 분포 - 데이터 분산 고려
ax1.set_title('Strip Plot')
ax2.set_title('Swarm Plot')
plt.savefig("graph/타이타닉호 age, class 산점도(seaborn모듈).png",dpi=400,bbox_inches="tight")
plt.show()
산점도(seaborn모듈 titanic 데이터셋)
seaborn모듈 titanic 데이터의 age컬럼, sex컬럼, class컬럼 - 타이타닉호 나이, 성별, 클래스 데이터 시각화
그래프 : 산점도
그래프 사용모듈 : seaborn
import seaborn as sns
import matplotlib.pyplot as plt
### 필요한 데이터 추출
# seaborn모듈 titanic(타이타닉호 데이터)데이터 데이터프레임 객체 생성
titanic = sns.load_dataset("titanic")
titanic.info()
### seaborn모듈 : 산점도
sns.set_style('whitegrid')
fig = plt.figure(figsize=(15, 5))
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
sns.stripplot(x="class", y="age",data=titanic,hue="sex", ax=ax1) # 이산형 변수의 분포 - 데이터 분산 미고려
sns.swarmplot(x="class", y="age",data=titanic,hue="sex", ax=ax2) # 이산형 변수의 분포 - 데이터 분산 고려
ax1.set_title('Strip Plot')
ax2.set_title('Swarm Plot')
plt.savefig("graph/타이타닉호 age, sex, class 산점도(seaborn모듈).png",dpi=400,bbox_inches="tight")
plt.show()
박스그래프, 바이올린그래프(seaborn모듈 titanic 데이터셋)
seaborn모듈 titanic 데이터의 alive컬럼, age컬럼, sex컬럼 - 타이타닉호 생존여부별 나이, 성별 데이터 시각화
그래프 : 박스그래프, 바이올린그래프
그래프 사용모듈 : seaborn
import seaborn as sns
import matplotlib.pyplot as plt
### 필요한 데이터 추출
# seaborn모듈 titanic(타이타닉호 데이터)데이터 데이터프레임 객체 생성
titanic = sns.load_dataset("titanic")
### seaborn모듈 : 박스그래프(값의 범주 표시), 바이올린그래프(값의 범주와 분포도를 표시)
'''
박스 그래프1 : 생존여부별 나이값에 대한 분포
박스 그래프2 : 생존여부별 나이값에 대한 분포 - 성별구분
# hue='sex'
바이올린그래프1 : 생존여부별 나이값에 대한 분포
바이올린그래프2 : 생존여부별 나이값에 대한 분포 - 성별구분
'''
fig = plt.figure(figsize=(15, 10))
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
ax4 = fig.add_subplot(2, 2, 4)
sns.boxplot(x='alive', y='age', data=titanic, ax=ax1) #박스그래프 - 기본값
sns.boxplot(x='alive', y='age', hue='sex', data=titanic, ax=ax2) #박스그래프 - hue 변수 추가
sns.violinplot(x='alive', y='age', data=titanic, ax=ax3) #바이올린그래프 - 기본값
sns.violinplot(x='alive', y='age', hue='sex', data=titanic,ax=ax4) #바이올그래프 - hue 변수 추가
ax2.legend(loc="upper center")
ax4.legend(loc="upper center")
plt.savefig("graph/타이타닉호 alive, age, sex 그래프들(seaborn모듈).png",dpi=400,bbox_inches="tight")
plt.show()
조인트그래프(seaborn모듈 titanic 데이터셋)
seaborn모듈 titanic 데이터의 age컬럼, fare컬럼 - 타이타닉호 나이, 요금 데이터 시각화
그래프 : 조인트그래프
그래프 사용모듈 : seaborn
import seaborn as sns
import matplotlib.pyplot as plt
### 필요한 데이터 추출
# seaborn모듈 titanic(타이타닉호 데이터)데이터 데이터프레임 객체 생성
titanic = sns.load_dataset("titanic")
### seaborn모듈 : 조인트그래프-산점도(기본값),x축y축데이터의 히스토그램
j1 = sns.jointplot(x='fare', y='age', data=titanic) #산점도(기본값)
j1.fig.suptitle('titanic fare - scatter', size=15) #차트제목표시
plt.savefig("graph/조인트그래프1(seaborn모듈).png",dpi=400,bbox_inches="tight")
j2 = sns.jointplot(x='fare', y='age', kind='reg',data=titanic) #회귀선(kind='reg')
j2.fig.suptitle('titanic fare - reg', size=15)
plt.savefig("graph/조인트그래프2.png",dpi=400,bbox_inches="tight")
j3 = sns.jointplot(x='fare', y='age', kind='hex',data=titanic) #육각그래프(kind='hex')
j3.fig.suptitle('titanic fare - hex', size=15)
plt.savefig("graph/조인트그래프3.png",dpi=400,bbox_inches="tight")
j4 = sns.jointplot(x='fare', y='age', kind='kde',data=titanic) #커럴밀집그래프(kind='kde')
j4.fig.suptitle('titanic fare - kde', size=15)
plt.savefig("graph/조인트그래프4.png",dpi=400,bbox_inches="tight")
FacetGrid(seaborn모듈 titanic 데이터셋)
seaborn모듈 titanic 데이터의 who컬럼, survived컬럼, age컬럼 - who, survived를 age기준으로 데이터 시각화
그래프 : FacetGrid - 조건에 따라 그리드 나누기
그래프 사용모듈 : seaborn
import seaborn as sns
import matplotlib.pyplot as plt
### 필요한 데이터 추출
titanic = sns.load_dataset("titanic")
# 3 * 2 = 6개의 그리드
titanic.who.value_counts() #who컬럼 값별 갯수(man, woman, child)
titanic.survived.value_counts() #survived컬럼 값별 갯수(0-구조안됨/1-구조됨)
### seaborn모듈 : FacetGrid-조건에 따라 그리드 나누기
g = sns.FacetGrid(data=titanic, col='who', row='survived')
g = g.map(plt.hist, 'age') #age컬럼을 기준으로 히스토그램을 표시.
plt.savefig("graph/FacetFrid.png",dpi=400,bbox_inches="tight")
plt.show()
pairplot(seaborn모듈 titanic 데이터셋)
seaborn모듈 titanic 데이터의 who컬럼, survived컬럼, age컬럼 - who, survived를 age기준으로 데이터 시각화
그래프 : FacetGrid - 각각의 컬럼별 이변수 데이터 분포 그리기
그래프 사용모듈 : seaborn
import seaborn as sns
import matplotlib.pyplot as plt
### 필요한 데이터 추출
titanic = sns.load_dataset("titanic")
#titanic 데이터셋 중에서 분석 데이터 선택하기
titanic_pair = titanic[['age','pclass', 'fare']]
print(titanic_pair)
### seaborn모듈 : pairplot-각각의 컬럼별 이변수 데이터 분포 그리기
# 각 변수들의 산점도 출력, 대각선 위치의 그래프는 히스토그램으로 표시.
g = sns.pairplot(titanic_pair)
plt.savefig("graph/pairplot.png",dpi=400,bbox_inches="tight")
'프로그래밍언어 > Python' 카테고리의 다른 글
[Python] follium 모듈 (1) | 2022.01.13 |
---|---|
[Python] 데이터 시각화 - 그래프 (0) | 2022.01.12 |
[Python] seaborn 모듈 (0) | 2022.01.12 |
[Python] pandas 모듈 (0) | 2022.01.12 |
[Python] Numpy 모듈 (0) | 2022.01.11 |