데브코스-데이터엔지니어링

Seaborn 시각화 라이브러리, 기상청 날씨 정보 시각화, 해시코드 질문태그 빈도 시각화, 단어구름 시각화

묠니르묘묘 2024. 4. 6. 18:40

Seaborn 시각화 라이브러리

  • Python의 데이터 시각화 라이브러리
  • 이를 활용하여 그래프 시각화
  • %pip install seaborn 으로 설치

 

Seaborn Essentials

# 시각화에 필요한 라이브러리를 불러와봅시다.
import seaborn as sns

 

꺾은선 그래프 (Line Plot)

  • 두 변수의 값에 따른 추이를 선으로 이은 그래프
  • `.lienplot()` 를 이용해서 그릴 수 있음
# Scatterplot을 직접 그려봅시다
sns.lineplot(x=[1, 3, 2, 4], y=[0.7,0.2,0.1,0.05])

 

막대 그래프 (Bar Plot)

  • 범주형 데이터의 값과 그 값의 크기를 직사각형으로 나타낸 그림
  • `.bar()` 를 이용해서 그릴 수 있음
# Barplot을 직접 그려봅시다
sns.barplot(x=["amy","bob","cat","dog"],y=[0.7,0.2,0.1,0.05])

 

Plot 속성

  • seaborn 은 파이썬 시각화 라이브러리 matplotlib 기반으로 만들어짐
  • matplotlib.pyplot 의 속성을 변경해서 그래프에 다양한 요소를 변경 및 추가 가능

 

그래프 제목 추가하기

# matplotlib.pyplot을 불러오기
import matplotlib.pyplot as plt

sns.barplot(x=[1,2,3,4],y=[0.7,0.2,0.1,0.05])

# 그래프 제목 추가하기
plt.title("Bar Plot")

# 보여주기
plt.show()

 

X, Y Label 추가하기

sns.barplot(x=[1,2,3,4],y=[0.7,0.2,0.1,0.05])

# xlabel과 ylabel 추가하기
plt.xlabel("X Label")
plt.ylabel("Y Label")

plt.show()

 

그래프 축 범위 지정하기

sns.lineplot(x=[1,3,2,4],y=[4,3,2,1])

# lineplot에서 ylim을 2~3으로 제한해봅시다.
plt.ylim(0, 10)

plt.show()

 

그래프 크기 지정하기

# 크기를 (20, 10)으로 지정해봅시다.
plt.figure(figsize=(20, 10))
sns.lineplot(x=[1,3,2,4],y=[4,3,2,1])
plt.show()

 

 

기상청 날씨 정보 시각화

# 스크래핑에 필요한 라이브러리를 불러와봅시다.

from selenium import webdriver
from selenium.webdriver import ActionChains
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver import Keys, ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

# driver를 이용해 기상청 날씨 데이터를 가져오기
driver = webdriver.Chrome()
driver.get("https://www.weather.go.kr/w/weather/forecast/short-term.do")
driver.implicitly_wait(2)
temps = driver.find_element(By.ID, "my-tchart").text

# 온도에서 "℃" 제거하여 숫자 배열 만들기
temps = [int(i) for i in temps.replace("℃", "").split("\n")]

# 받아온 데이터를 통해 꺾은선 그래프 그려보기
import seaborn as sns

sns.lineplot(
    x = [i for i in range(len(temps))],
    y = temps
)

# 받아온 데이터를 통해 꺾은선 그래프를 그리고, 그래프 축 범위와 제목 지정하기
import matplotlib.pyplot as plt

plt.ylim(min(temps)-2, max(temps) + 2)
plt.title("Expected Temperature from now on")

sns.lineplot(
    x = [i for i in range(len(temps))],
    y = temps
)

plt.show()

 

해시코드 질문태그 빈도 시각화

# User-Agent 추가
user_agent = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36"}

# 필요한 라이브러리를 불러온 후, 요청을 진행
import time
import requests
from bs4 import BeautifulSoup

# 질문의 빈도를 체크하는 dict를 만든 후, 빈도를 체크
frequency = {}

for i in range(1, 11):
    res = requests.get("https://hashcode.co.kr/?page={}".format(i), user_agent)
    soup = BeautifulSoup(res.text, "html.parser")

    # 1. ul 태그를 모두 찾기
    # 2. 1번 안에 있는 li 태그의 text 추출

    ul_tags = soup.find_all("ul", "question-tags")
    for ul in ul_tags:
        li_tags = ul.find_all("li")
        for li in li_tags:
            tag = li.text.strip()
            if tag not in frequency:
                frequency[tag] = 1
            else:
                frequency[tag] += 1
    time.sleep(0.5)

# Counter를 사용해 가장 빈도가 높은 value들을 추출
from collections import Counter

counter = Counter(frequency)

# Seaborn을 이용해 이를 Barplot으로 그리기
import seaborn as sns

x = [elem[0] for elem in counter.most_common(10)]
y = [elem[1] for elem in counter.most_common(10)]

# figure, xlabel, ylabel, title을 적절하게 설정해서 시각화 완성
import matplotlib.pyplot as plt

plt.figure(figsize=(20, 10))
plt.title("Frequency of question in Hashcode")
plt.xlabel("Tag")
plt.ylabel("Frequency")

sns.barplot(x=x, y=y)
plt.show()

 

 

뭉게뭉게 단어구름 시각화

wordcloud 라이브러리

  • Python의 텍스트 클라우드 라이브러리
  • 이를 기반으로 텍스트 구름 그릴 수 있음
  • konlpy : 한국어 형태소 분석기 라이브러리로, 주어진 문장에서 명사 등을 뽑아 내는 데에 사용 가능
  • `%pip install wordcloud`
  • `%pip install konlpy`

 

# 텍스트 구름을 그리기 위해 필요한 라이브러리를 불러오기

# 시각화에 쓰이는 라이브러리
import matplotlib.pyplot as plt
from wordcloud import WordCloud

# 횟수를 기반으로 딕셔너리 생성
from collections import Counter

# 문장에서 명사를 추출하는 형태소 분석 라이브러리
from konlpy.tag import Hannanum

# 워드클라우드를 만드는 데 사용할 애국가 가사
national_anthem = """
동해물과 백두산이 마르고 닳도록
하느님이 보우하사 우리나라 만세
무궁화 삼천리 화려 강산
대한 사람 대한으로 길이 보전하세
남산 위에 저 소나무 철갑을 두른 듯
바람 서리 불변함은 우리 기상일세
무궁화 삼천리 화려 강산
대한 사람 대한으로 길이 보전하세
가을 하늘 공활한데 높고 구름 없이
밝은 달은 우리 가슴 일편단심일세
무궁화 삼천리 화려 강산
대한 사람 대한으로 길이 보전하세
이 기상과 이 맘으로 충성을 다하여
괴로우나 즐거우나 나라 사랑하세
무궁화 삼천리 화려 강산
대한 사람 대한으로 길이 보전하세
"""

# 형태소 분석기 객체를 사용하여 주어진 문자열에서 명사 추출하기
# Hannanum 객체를 생성한 후, .nouns()를 통해 명사를 추출
hannanum = Hannanum()
nouns = hannanum.nouns(national_anthem)
words = [noun for noun in nouns if len(noun) > 1]

# counter를 이용해 각 단어의 개수를 세기
counter = Counter(words)

# WordCloud를 이용해 텍스트 구름을 만들기
# 이 때, font_path는 한글을 그려주기 위한 폰트를 지정해야해서 각 컴퓨터의 폰트경로 지정
wordcloud = WordCloud(
    font_path="/Users/yong/Library/Fonts/함초롱돋움R.ttf",
    background_color="white",
    width=1000,
    height=1000
)

img = wordcloud.generate_from_frequencies(counter)
plt.imshow(img)