# 크기를 (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)