24.01.25 목
Seaborn
Seaborn이란?
matplotlib을 기반으로 하는 파이썬 시각화 라이브러리.
matplotlib과 seaborn의 차이
궁금해서 서치도 해보고, gpt에게도 물어보았다.
Seaborn 사용법
% pip install seaborn
# 시각화에 필요한 라이브러리를 불러와봅시다.
import seaborn as sns
# 꺾은선 그래프 - lineplot을 직접 그려봅시다.
sns.lineplot(x=[1, 3, 2, 4], y=[4, 3, 2, 1])
# 막대 그래프 - barplot을 직접 그려봅시다.
sns.barplot(x=[1,2,3,4],y=[0.7,0.2,0.1,0.05])
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")
# xlabel과 ylabel을 추가해봅시다.
sns.barplot(x=[1,2,3,4], y=[0.7,0.2,0.1,0.05])
plt.xlabel("X Label")
plt.ylabel("Y Label")
# 크기를 (20, 10)으로 지정해봅시다.
plt.figure(figsize = (20, 10))
sns.lineplot(x=[1, 3, 2, 4], y=[4, 3, 2, 1])
plt.show()
Example gallery — seaborn 0.13.2 documentation
seaborn.pydata.org
예제 - 기상청 날씨 스크래핑
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를 이용해 기상청 날씨 데이터를 가져와봅시다.
import time
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://www.weather.go.kr/w/weather/forecast/short-term.do")
driver.implicitly_wait(10)
temps = driver.find_element(By.ID, "my-tchart").text
temps = [int(i) for i in temps.replace("℃", "").split("\n")]
print(temps)
# 받아온 데이터를 통해 꺾은선 그래프를 그려봅시다.
# x = Elapsed Time(0~len(temperatures)
# y = temperatures
import seaborn as sns
import matplotlib.pyplot as plt
# 받아온 데이터의 ylim을 조금 더 길게 잡아봅시다.
plt.ylim(min(temps) - 4, max(temps) + 4)
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": "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 requests
from bs4 import BeautifulSoup
res = requests.get("https://qna.programmers.co.kr/")
import time
frequency = {}
for i in range(1, 11):
res = requests.get("https://qna.programmers.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)
print(frequency)
# Counter를 사용해 가장 빈도가 높은 value들을 추출합니다.
from collections import Counter
counter = Counter(frequency)
# 상위 10개
counter.most_common(10)
# 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)]
sns.barplot(x=x, y=y)
# 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
Wordcloud란?
파이썬의 텍스트 클라우드 라이브러리.
% pip install wordcloud
% pip install konlpy
Wordcloud 만드는 방법
- KoNLPy 라이브러리로 한국어 문장을 전처리
- Counter를 이용해 빈도수 측정
- WordCloud를 이용해 시각화
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]
words[:10]
# counter를 이용해 각 단어의 개수를 세줍니다.
counter = Counter(words)
print(counter)
# WordCloud를 이용해 텍스트 구름을 만들어봅시다.
wordcloud = WordCloud(
font_path= "/Users/kim-seungeon/Library/Fonts/A고속도로.TTF",
background_color="white",
width=1000,
height=1000
)
img = wordcloud.generate_from_frequencies(counter)
plt.imshow(img)
예제 - 해시코드 질문 키워드로 워드클라우드 만들기
# 다음 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 requests
import time
from bs4 import BeautifulSoup
questions = []
for i in range(1, 6):
res = requests.get("https://qna.programmers.co.kr/?page={}".format(i), user_agent)
soup = BeautifulSoup(res.text, "html.parser")
parsed_datas = soup.find_all("li", "question-list-item")
for data in parsed_datas:
questions.append(data.h4.text.strip())
# 과도한 요청을 방지하기 위해 0.5초마다 요청을 보내봅시다.
time.sleep(0.5)
print(questions[:10])
# 워드클라우드 만들기
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from collections import Counter
from konlpy.tag import Hannanum
words = []
hannanum = Hannanum()
for question in questions:
nouns = hannanum.nouns(question)
words += nouns
print(len(words))
counter = Counter(words)
counter
wordcloud = WordCloud(
font_path="/Users/kim-seungeon/Library/Fonts/A고속도로.TTF",
background_color="white",
height=1000,
width=1000
)
img = wordcloud.generate_from_frequencies(counter)
plt.imshow(img)
'[프로그래머스] 데이터엔지니어링 데브코스 1기 > TIL (Today I Learned)' 카테고리의 다른 글
TIL_day27 AWS RDS, Dynamo DB, Route53, ELB, VPC (0) | 2024.02.14 |
---|---|
TIL_day25 Transaction (1) | 2024.01.31 |
TIL_day9 Selenium (1) | 2024.01.24 |
TIL_day8 Beautifulsoup (1) | 2024.01.24 |
셀레니움 크롬드라이버 설치(버전 이슈) (1) | 2024.01.21 |