본문 바로가기

제로베이스/Python

Python 10. Visualization

파이썬 기초 익히기 10

 

#파이썬 시각화를 위한 기본 세팅

import pandas as pd

# visualization libraries
import matplotlib.pyplot as plt
import seaborn as sns


# print the graphs in the notebook
%matplotlib inline

# set seaborn style to white
sns.set_style("white")

 

Q114. 'Unnamed: 0' Column을 삭제하시오

#1
del df['Unnamed: 0']
df.head()

#2 
df = df['total_bill','tip','sex','smoker','day','time','size']
## 최대한 원본 데이터는 변형하지 않는 게 좋음 
## 필요한 데이터를 뽑아서 쓰자

 

Q115. total_bill에 대해서 히스토그램을 그리시오

ttbill = sns.histplot(df.total_bill);

# set lables and titles
ttbill.set(xlabel = 'Value',ylabel = 'Frequency', title = 'Total Bill');

Q116. total_bill과 tip에 대해서 jointplot을 그리시오

sns.jointplot(x='total_bill', y='tip', data =df);

Q117. 모든 연속성 변수에 대해서 pairplot을 그리시오

sns.pairplot(df);
##연속형 변수에 대해서만 만들 수 있음
##변수가 많아지면 비추(10개 이하)

Q118. day에 따라 total_bill의 관계를 파악하기 위한 stripplot을 그리시오

sns.stripplot(x='day',y='total_bill',data = df, hue ='day'); ## hue는 색상 구분 기준
# sns.stripplot(x = "day", y = "total_bill", data = df);

Q119. day와 성별에 따라 tip의 관계를 파악하기 위한 stripplot을 그리시오 ( x축 - tip, y축 - day)

sns.stripplot(x='tip',y='day',data=df,hue='sex');

Q120. day와 time에 따라 total_bill의 관계를 파악하기 위한 boxplot을 그리시오 ( x축 - day, y축 - total_bill)

sns.boxplot(x= 'day', y = 'total_bill', hue = 'time' ,data =df);
## 중앙선은 median(평균X)

Q121. 저녁(Dinner)과 점심(Lunch)을 기준으로 한 팁 값에 대해 두 개의 히스토그램을 생성하세요.

## 이건 굳이 안해도 되는 옵션(그래프 예쁘게 하려고)
# better seaborn style
# sns.set(style = "ticks")
# plt.grid(True)

# creates FacetGrid
g = sns.FacetGrid(df, col = time) ## time을 기준으로 grid 나눔 
g.map(plt.hist,'tip');
## plt.hist 대신 sns.histplot도 사용 가능

Q121. 남성과 여성을 대상으로 한 두 개의 산점도 그래프를 생성하세요. 이 그래프들은 전체 청구 금액(total_bill)과 팁(tip) 간의 관계를 보여주며, 흡연자와 비흡연자로 구분되어야 합니다.

## plt.scatter: 산점도 
g = sns.FacetGrid(df,col = 'sex',hue = "smoker")
g.map(plt.scatter,'total_bill','tip',alpha =.7) ##alpha: 투명도

g.add_legend(); ## 범례표현

Q122. PassengerId를 인덱스로 설정하시오.

df.set_index('PassengerId', inplace=True)
df.head()

 

Q123. 남성과 여성의 비율을 나타내는 파이 차트를 생성하세요.

## 파이썬으로 파이차트를 그리는 건 비효율적..
# sum the instances of males and females(숫자)
males = (df['Sex'] == 'male').sum()
females = (df['Sex'] == 'female').sum()

# put them into a list called proportions
proportions = [males, females]

# Create a pie chart
plt.pie(
    # using proportions
    proportions,

    # with the labels being officer names
    labels = ['Males', 'Females'],
    
    ## 여기서부터는 선택사항
    # with no shadows
    shadow = False,

    # with colors
    colors = ['blue','red'],

    # with one slide exploded out
    explode = (0.15 , 0),

    # with the start angle at 90%
    startangle = 90,

    # with the percent listed as a fraction
    autopct = '%1.1f%%'
    )

# View the plot drop above
plt.axis('equal')

# Set labels
plt.title("Sex Proportion")

# View the plot
plt.tight_layout()
plt.show()

Q124. 지불한 요금(Fare)과 나이(Age)를 나타내는 산점도를 생성하세요. 그래프의 색상은 성별에 따라 달라져야 합니다.

# creates the plot using
lm = sns.lmplot(x= 'Age', y = 'Fare', data = df, hue = 'sex', fit_reg =False) 
## fit_reg 회귀선옵션

# set title
lm.set(title = 'Fare x Age')

# get the axes object and tweak it(축 범위 설정)
axes = lm.axes
axes[0,0].set_ylim(-5,)
axes[0,0].set_xlim(-5,85)

Q125. 지불한 요금(Fare)에 대한 히스토그램을 생성하세요

import numpy as np
# sort the values from the top to the least value and slice the first 5 items
df2 = df.Fare.sort_values(ascending = False) ## bin 설정할 때 max값 확인하려고 sorting

# create bins interval using numpy
binsVal = np.arange(0,600,10) ##0부터 10씩 뛰어세면서 590까지 출력(파이썬은 마지막은 출력안함 600X)
binsVal

# create the plot
plt.hist(df2, bins = binsVal)

# Set the title and labels
plt.xlabel('Fare')
plt.ylabel('Frequency')
plt.title('Fare Payed Histrogram')

# show the plot
plt.show()

 

참고)

jointplot은 차트의 중앙에 그래프를 하나 보여주고, 그래프의 상단과 오른쪽에 marginal 그래프를 보여주는 그래프

중앙에는 산점도 플롯, 리그레션 플롯, 커널밀도플롯 등을 사용할 수 있고,

상단과 오른쪽에는 히스토그램과 커널밀도플롯을 사용하여 두 변수의 분포를 보여주는 것이 가능

 

 

'제로베이스 > Python' 카테고리의 다른 글

Python 11.Deleting  (0) 2024.07.01
Python 9. Series & DataFrame  (0) 2024.07.01
Python 8. Statistics  (0) 2024.06.29
Python 7. Merge, Concat  (0) 2024.06.29
Python 6. Pivot  (0) 2024.06.29