728x90
In [1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams['font.family'] = 'Malgun Gothic' # 한글 폰트 사용
plt.rcParams['font.size'] = 20 # Matplotlib 폰트 사이즈 변경
plt.rcParams['axes.unicode_minus'] = False # 한글 폰트 사용 시, 마이너스 글자가 깨지는 현상해결
Matplotlib
In [2]:
# In[21]:
import matplotlib.pyplot as plt
plt.figure(figsize=(5,3))
x = [1,2,3,4]
y = [2,4,5,9]
plt.plot(x,y)
Out[2]:
[<matplotlib.lines.Line2D at 0x15e03bff2d0>]
In [3]:
# In[22]:
import matplotlib.pyplot as plt
plt.style.use('ggplot')
plt.figure(figsize=(5,3))
x = [1,2,3,4]
y = [2,4,5,9]
plt.plot(x,y)
Out[3]:
[<matplotlib.lines.Line2D at 0x15e03c47dd0>]
In [4]:
# In[23]:
import matplotlib.pyplot as plt
plt.figure(figsize=(5,3))
plt.style.use('ggplot')
x = range(0,10)
y = range(5,15)
plt.plot(x,y , 'ro')
Out[4]:
[<matplotlib.lines.Line2D at 0x15e03c46390>]
In [5]:
# In[24]:
# x축 범위와 y축 범위 지정하기
import matplotlib.pyplot as plt
plt.figure(figsize=(5,3))
plt.style.use('ggplot')
plt.xlim(1,10)
plt.ylim(0,15)
x = range(0,10)
y = range(5,15)
plt.plot(x,y , 'ro')
Out[5]:
[<matplotlib.lines.Line2D at 0x15e03c70a10>]
In [6]:
# In[29]:
import matplotlib.pyplot as plt
plt.figure(figsize=(5,3))
plt.style.use('ggplot')
x = range(0,10)
y = range(5,15)
plt.plot(x,y , 'ro')
plt.xlabel('time')
plt.ylabel('qty')
Out[6]:
Text(0, 0.5, 'qty')
In [7]:
# In[30]:
import matplotlib.pyplot as plt
plt.figure(figsize=(5,3))
plt.style.use('ggplot')
x = range(0,10)
y = range(5,15)
plt.plot(x,y , 'ro')
plt.xlabel('판매시간')
plt.ylabel('판매수량')
Out[7]:
Text(0, 0.5, '판매수량')
In [8]:
# In[31]:
from matplotlib import pyplot as plt
import matplotlib.font_manager as fm
import matplotlib
font_location = "C:\\Windows\\Fonts\\malgun.ttf"
font_name = fm.FontProperties(fname = font_location).get_name()
matplotlib.rc('font' , family=font_name)
plt.figure(figsize=(5,3))
plt.style.use('ggplot')
x = range(0,10)
y = range(5,15)
plt.plot(x,y , 'ro')
plt.xlabel('판매시간')
plt.ylabel('판매수량')
Out[8]:
Text(0, 0.5, '판매수량')
In [9]:
# In[32]:
#bar chart
import matplotlib.pyplot as plt
plt.figure(figsize=(5,3))
plt.style.use('ggplot')
x = [3,5] # 막대 사이 간격 조정용
y = [1,2]
plt.bar(x,y)
Out[9]:
<BarContainer object of 2 artists>
In [10]:
# In[33]:
#bar chart
import matplotlib.pyplot as plt
plt.figure(figsize=(5,3))
plt.style.use('ggplot')
x = [3,5] # 막대 사이 간격 조정용
y = [1,2]
labels = ['english','math']
plt.bar(x,y , tick_label = labels)
Out[10]:
<BarContainer object of 2 artists>
In [11]:
#In[34]:
#bar chart
import matplotlib.pyplot as plt
plt.figure(figsize=(5,3))
plt.style.use('ggplot')
x = [3,4] # 막대 사이 간격 조정용
y = [1,2]
colors = ['red','blue']
labels = ['english','math']
#width 는 막대의 두께이고 기본값은 0.8 입니다.
plt.bar(x,y , tick_label = labels , color = colors , width=0.4)
Out[11]:
<BarContainer object of 2 artists>
In [12]:
# In[2]:
#bar chart
import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=(5,3))
plt.style.use('ggplot')
x = [3,4] # 막대 사이 간격 조정용
y = [1,2]
# 색상을 데이터 건수만큼 랜덤으로 생성하기
colors = [np.random.rand(3,) for _ in x]
labels = ['english','math']
#width 는 막대의 두께이고 기본값은 0.8 입니다.
plt.bar(x,y , tick_label = labels , color = colors , width=0.4)
Out[12]:
<BarContainer object of 2 artists>
In [13]:
# In[3]:
#y축 간격 지정하기
import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=(5,3))
plt.style.use('ggplot')
x = [3,4] # 막대 사이 간격 조정용
y = [1,2]
# 색상을 데이터 건수만큼 랜덤으로 생성하기
colors = [np.random.rand(3,) for _ in x]
labels = ['english','math']
# 축 간격 수동으로 지정하기
from matplotlib.ticker import MultipleLocator
plt.gca().yaxis.set_major_locator(MultipleLocator(base=0.1))
#width 는 막대의 두께이고 기본값은 0.8 입니다.
plt.bar(x,y , tick_label = labels , color = colors , width=0.4)
Out[13]:
<BarContainer object of 2 artists>
In [14]:
# In[4]:
# x 축 값을 기울여 출력하기
import matplotlib.pyplot as plt
plt.figure(figsize=(5,3))
plt.style.use('ggplot')
x = [3,4] # 막대 사이 간격 조정용
y = [1,2]
colors = ['red','blue']
labels = ['english','math']
#width 는 막대의 두께이고 기본값은 0.8 입니다.
plt.bar(x,y , tick_label = labels , color = colors , width=0.4)
plt.xticks(rotation=45)
Out[14]:
(array([3, 4]), [Text(3, 0, 'english'), Text(4, 0, 'math')])
In [15]:
# In[35]:
import pandas as pd
data1 = pd.DataFrame({'번호' : [1,2,3,4,5],
'이름' : ['홍길동','일지매','이순신','유관순','서진수'],
'몸무게' : [80, 85, 70,75,83],
'키' : [180, 185, 170 ,175,183]})
data1
Out[15]:
번호 | 이름 | 몸무게 | 키 | |
---|---|---|---|---|
0 | 1 | 홍길동 | 80 | 180 |
1 | 2 | 일지매 | 85 | 185 |
2 | 3 | 이순신 | 70 | 170 |
3 | 4 | 유관순 | 75 | 175 |
4 | 5 | 서진수 | 83 | 183 |
In [16]:
# In[36]:
from matplotlib import pyplot as plt
import matplotlib.font_manager as fm
import matplotlib
font_location = "C:\\Windows\\Fonts\\malgun.ttf"
font_name = fm.FontProperties(fname = font_location).get_name()
matplotlib.rc('font' , family=font_name)
plt.figure(figsize=(5,3))
colors = ['red','green','yellow','orange','violet']
x = data1['이름']
y = data1['몸무게']
plt.bar(x,y , color = colors , width=0.5)
plt.title('학생별 몸무게')
plt.ylabel('몸무게(단위:Kg)')
plt.xlabel('이름')
Out[16]:
Text(0.5, 0, '이름')
In [17]:
# In[37]:
from matplotlib import pyplot as plt
import matplotlib.font_manager as fm
import matplotlib
font_location = "C:\\Windows\\Fonts\\malgun.ttf"
font_name = fm.FontProperties(fname = font_location).get_name()
matplotlib.rc('font' , family=font_name)
plt.figure(figsize=(5,3))
colors = ['red','green','yellow','orange','violet']
x = data1['이름']
y = data1['몸무게']
plt.bar(x,y , color = colors , width=0.5)
plt.title('학생별 몸무게')
plt.ylabel('몸무게(단위:Kg)')
plt.xlabel('이름')
plt.savefig('c:\\py_temp\\학생별몸무게.png')
plt.savefig('c:\\py_temp\\학생별몸무게.pdf')
In [18]:
# 화면 분할하기
# In[1]:
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
x = range(0,10)
y = range(5,15)
ax1.plot(x,y , 'ro')
x = range(0,50)
y = range(0,50)
ax2.plot(x,y , 'bs')
plt.show()
In [19]:
# In[2]:
fig = plt.figure()
ax1 = fig.add_subplot(1, 3, 1)
ax2 = fig.add_subplot(1, 3, 3)
x = range(0,10)
y = range(5,15)
ax1.plot(x,y , 'ro')
x = range(0,50)
y = range(0,50)
ax2.plot(x,y , 'bs')
ax1.set_xlabel('time')
ax1.set_ylabel('qty')
ax2.set_xlabel('시간')
ax2.set_ylabel('qty')
plt.show()
Seaborn¶
In [20]:
sns.set_theme(style = 'darkgrid')
tips = sns.load_dataset('tips')
tips
Out[20]:
total_bill | tip | sex | smoker | day | time | size | |
---|---|---|---|---|---|---|---|
0 | 16.99 | 1.01 | Female | No | Sun | Dinner | 2 |
1 | 10.34 | 1.66 | Male | No | Sun | Dinner | 3 |
2 | 21.01 | 3.50 | Male | No | Sun | Dinner | 3 |
3 | 23.68 | 3.31 | Male | No | Sun | Dinner | 2 |
4 | 24.59 | 3.61 | Female | No | Sun | Dinner | 4 |
... | ... | ... | ... | ... | ... | ... | ... |
239 | 29.03 | 5.92 | Male | No | Sat | Dinner | 3 |
240 | 27.18 | 2.00 | Female | Yes | Sat | Dinner | 2 |
241 | 22.67 | 2.00 | Male | Yes | Sat | Dinner | 2 |
242 | 17.82 | 1.75 | Male | No | Sat | Dinner | 2 |
243 | 18.78 | 3.00 | Female | No | Thur | Dinner | 2 |
244 rows × 7 columns
In [21]:
graph1 = sns.histplot(tips , x='total_bill', bins = 20) # bins: 구간 지정
In [22]:
titanic = sns.load_dataset('titanic')
titanic.head()
Out[22]:
survived | pclass | sex | age | sibsp | parch | fare | embarked | class | who | adult_male | deck | embark_town | alive | alone | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0 | 3 | male | 22.0 | 1 | 0 | 7.2500 | S | Third | man | True | NaN | Southampton | no | False |
1 | 1 | 1 | female | 38.0 | 1 | 0 | 71.2833 | C | First | woman | False | C | Cherbourg | yes | False |
2 | 1 | 3 | female | 26.0 | 0 | 0 | 7.9250 | S | Third | woman | False | NaN | Southampton | yes | True |
3 | 1 | 1 | female | 35.0 | 1 | 0 | 53.1000 | S | First | woman | False | C | Southampton | yes | False |
4 | 0 | 3 | male | 35.0 | 0 | 0 | 8.0500 | S | Third | man | True | NaN | Southampton | no | True |
In [23]:
graph4 = sns.countplot(titanic , x='who', hue = 'class' )
산점도 그래프(Scatter)¶
In [24]:
tips = sns.load_dataset('tips')
graph7 = sns.scatterplot(tips , x='total_bill' , y = 'tip', hue ='sex')
In [25]:
import seaborn as sns
import warnings
warnings.filterwarnings("ignore", category=UserWarning, module="seaborn")
sns.set(style="whitegrid")
data1 = sns.load_dataset('tips')
sns.relplot(data=data1 , x='total_bill',y='tip',hue='smoker')
Out[25]:
<seaborn.axisgrid.FacetGrid at 0x15e063e15d0>
In [26]:
graph = sns.catplot(data=data1 , x='day',y='total_bill',hue='smoker',col='time')
graph.set_xticklabels(rotation=90)
Out[26]:
<seaborn.axisgrid.FacetGrid at 0x15e06539d50>
In [27]:
sns.pairplot(data1)
Out[27]:
<seaborn.axisgrid.PairGrid at 0x15e065cb810>
In [28]:
#headmap 예제 데이터 생성하기
import pandas as pd
data = pd.DataFrame( { '연령대':['10대','20대','30대','40대','50대'] ,
'Bus' : [88,92,95,75, 97] ,
'Subway' : [70,80,95,85,80] ,
'Car' : [20,50,90,95,99]})
data.set_index('연령대', drop=True , inplace=True)
data
Out[28]:
Bus | Subway | Car | |
---|---|---|---|
연령대 | |||
10대 | 88 | 70 | 20 |
20대 | 92 | 80 | 50 |
30대 | 95 | 95 | 90 |
40대 | 75 | 85 | 95 |
50대 | 97 | 80 | 99 |
In [29]:
# 한글 폰트 지정하기
from matplotlib import pyplot as plt
import matplotlib.font_manager as fm
import matplotlib
font_location = "C:\\Windows\\Fonts\\malgun.ttf"
font_name = fm.FontProperties(fname = font_location).get_name()
matplotlib.rc('font' , family=font_name)
#히트맵으로 시각화하기 - 1
sns.heatmap(data)
Out[29]:
<Axes: ylabel='연령대'>
In [30]:
#히트맵으로 시각화하기 - 2 - 그래프 크기 지정하기
fig , ax = plt.subplots(1,1,figsize=(10,7) )
sns.heatmap(data, annot = True)
Out[30]:
<Axes: ylabel='연령대'>
Quiz¶
In [31]:
# 데이터 불러오기
file1 = pd.read_csv('C:\py_temp\부품구입대장_전체.csv', encoding ='cp949')
# 사업장명이 '석수'인 데이터의 사업장, 품목, 수량 컬럼 추출
file2 = file1[file1['사업장'] == '석수'][['사업장', '품목', '수량']]
# 사업장, 품목으로 그룹핑 후 수량의 합계를 구하여 head(5)
file3 = file2.groupby(['사업장','품목'], as_index = False)['수량'].sum().head(5)
# 수량 값이 큰 순서부터 출력
file4 = file3.sort_values(['수량'], ascending = False)
file4
Out[31]:
사업장 | 품목 | 수량 | |
---|---|---|---|
4 | 석수 | AL TAPE | 143 |
1 | 석수 | AIR COUPLER | 99 |
2 | 석수 | AIR CYLINDER | 98 |
0 | 석수 | AIR BOX | 36 |
3 | 석수 | AIR MODULAR UNIT | 10 |
In [32]:
# 색상을 데이터 건수만큼 랜덤으로 생성하기
colors = [np.random.rand(3,) for _ in x]
# 데이터 막대그래프로 시각화
plt.figure(figsize = (20,10))
plt.bar((file4['품목']),(file4['수량']), color = colors)
# 그래프 축
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
# label 지정
plt.xlabel('품목', fontsize = 20)
plt.ylabel('수량', fontsize = 20)
plt.title('품목별 수량', fontsize = 20 )
Out[32]:
Text(0.5, 1.0, '품목별 수량')
In [ ]:
In [ ]:
In [ ]:
In [ ]:
728x90
'PYTHON > 기타' 카테고리의 다른 글
[나도코딩] 파이썬 웹 스크래핑(Web Scraping)(User_Agent, BeautifulSoup4) (2) | 2024.01.10 |
---|---|
[데이터 분석] 파이썬 태양열 신재생 에너지 분석(수평면 산란 일사량,풍속과 태양열 발전량의 상관관계) (0) | 2024.01.05 |
[데이터 분석] Pandas 연습 (0) | 2024.01.05 |
[나도코딩] 파이썬 웹스크래핑(Web Scraping)(HTML, XPath, Requests, 정규식) (2) | 2023.12.23 |
[데이터 분석] 파이썬 쇼핑몰 매출 분석(월별, 요일별, 품목별, 연령대별)을 통한 인사이트 도출과 마케팅 전략 제안 (0) | 2023.12.12 |