matplotlib을 기반으로 하는 시각화 라이브러리
다양한 그래프를 고수준(high-level)에서 쉽게 그릴 수 있다.
# 라이브러리 다운
%pip install seaborn
두 변수의 값에 따른 추이를 선으로 이은 그래프
# 시각화에 필요한 라이브러리를 불러와봅시다.
import seaborn as sns
# Scatterplot을 직접 그려봅시다
# 값 x=[1, 3, 2, 4]
# 값 y=[0.7,0.2,0.1,0.05]
sns.lineplot(x=[1, 3, 2, 4], y=[4, 3, 2, 1])
범주형 데이터의 "값"과 그 값의 크기를 직사각형으로 나타낸 그림
# Barplot을 직접 그려봅시다
# 범주 x=["Amy","Bob", "Cat", "Dog"]
# 값 y=[0.7,0.2,0.1,0.05]
sns.barplot(x=["Amy","Bob", "Cat", "Dog"],y=[0.7,0.2,0.1,0.05])
matplotlib.pyplot의 속성을 변경해서 그래프에 다양한 요소를 변경/추가할 수 있습니다.
plt.title(): 그래프에 제목을 추가
plt.xlabel(): 그래프의 축에 설명을 추가합니다
plt.ylim(): 그래프의 축의 범위를 지정합니다.
plt.figure(figsize=(x,y)): 그래프의 크기를 지정합니다.
# 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()
# 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")
plt.show()
# lineplot에서 ylim을 2~3으로 제한해봅시다.
sns.lineplot(x=[1, 3, 2, 4], y=[4, 3, 2, 1])
plt.ylim(2,3)
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(service=Service(ChromeDriverManager().install()))
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")]
print(temps)
# 받아온 데이터를 통해 꺾은선 그래프를 그려봅시다.
# x = Elapsed Time(0~len(temperatures)
# y = temperatures
import seaborn as sns
sns.lineplot(
x = [i for i in range(len(temps))],
y = temps
)
# 받아온 데이터의 ylim을 조금 더 길게 잡아봅시다.
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
)
# 다음 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"}
# 필요한 라이브러리를 불러온 후, 요청을 진행해봅시다.
# 응답을 바탕으로 BeautifulSoup 객체를 생성해봅시다.
# 질문의 빈도를 체크하는 dict를 만든 후, 빈도를 체크해봅시다.
import requests
from bs4 import BeautifulSoup
import time
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)
print(frequency)
# Counter를 사용해 가장 빈도가 높은 value들을 추출합니다.
from collections import Counter
counter = Counter(frequency)
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는 파이썬의 텍스트 클라우드 라이브러리입니다. 이를 기반으로 텍스트 구름을 그릴 수 있습니다.
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)
nouns[:10]
# counter를 이용해 각 단어의 개수를 세줍니다.
counter = Counter(nouns)
# WordCloud를 이용해 텍스트 구름을 만들어봅시다.
wordcloud = WordCloud(
background_color="white",
width=1000,
height=1000,
)
img = wordcloud.generate_from_frequencies(counter)
plt.imshow(img)
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"}
# Pagination이 되어있는 질문 리스트의 제목을 모두 가져와 리스트 questions에 저장해봅시다.
# https://hashcode.co.kr/?page={i}
# 과도한 요청을 방지하기 위해 0.5초마다 요청을 보내봅시다.
import requests
from bs4 import BeautifulSoup
questions = []
import time
for i in range(1,6):
res = requests.get("https://hashcode.co.kr/?page={}".format(i), {"User-Agent":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())
time.sleep(0.5)
questions[:10]
# 텍스트 구름을 그리기 위해 필요한 라이브러리를 불러와봅시다.
# 시각화에 쓰이는 라이브러리
import matplotlib.pyplot as plt
from wordcloud import WordCloud
# 횟수를 기반으로 딕셔너리 생성
from collections import Counter
# 문장에서 명사를 추출하는 형태소 분석 라이브러리
from konlpy.tag import Hannanum
# Hannanum 객체를 생성한 후, .nouns()를 통해 명사를 추출합니다.
words = []
hannanum = Hannanum()
for question in questions:
nouns = hannanum.nouns(question)
words += nouns
print(len(words))
# counter를 이용해 각 단어의 개수를 세줍니다.
counter = Counter(words)
# WordCloud를 이용해 텍스트 구름을 만들어봅시다.
wordcloud = WordCloud(
font_path="...",
background_color="white"
height=1000,
width=1000
)
img = wordcloud.generate_from_frequencies(counter)
plt.imshow(img)