본문 바로가기
Python

Django 웹앱에 시각화 추가하기 – 감성 차트 & 워드클라우드 이미지 출력

by ramzee 2025. 4. 14.

0. 이 글은 누구를 위한 글인가요?

  • 분석 결과를 숫자가 아닌 시각적으로 보여주고 싶은 분
  • Django 웹에서 감성 분석 차트나 워드클라우드를 삽입하고 싶은 분
  • Matplotlib, WordCloud, KoNLPy를 웹 화면에 연동하고 싶은 분

1. 프로젝트 목표

  • 감성 비율 시각화: 긍정/부정/중립 비율을 막대 그래프로 출력
  • 워드클라우드 시각화: 자주 등장하는 키워드를 이미지로 시각화

2. 필요한 추가 라이브러리 설치

pip install matplotlib wordcloud konlpy

3. 시각화 이미지 저장 폴더 생성

mkdir -p static/images

static/images/ 폴더에 결과 이미지를 저장합니다.


4. views.py에 시각화 함수 추가

4-1. 추가 import

import matplotlib.pyplot as plt
from wordcloud import WordCloud
from konlpy.tag import Okt
from collections import Counter
import os
4-2. 감성 차트 그리기

def draw_sentiment_bar(sentiments, save_path):
    counts = Counter(sentiments)
    labels = list(counts.keys())
    values = list(counts.values())

    plt.figure(figsize=(6, 4))
    plt.bar(labels, values, color=['red', 'gray', 'green'])
    plt.title("감성 분석 결과")
    plt.xlabel("감성")
    plt.ylabel("개수")
    plt.tight_layout()
    plt.savefig(save_path)
    plt.close()
4-3. 워드클라우드 생성

def generate_wordcloud(titles, save_path):
    okt = Okt()
    text = " ".join(titles)
    nouns = okt.nouns(text)
    words = [word for word in nouns if len(word) > 1]
    word_freq = Counter(words)

    font_path = "C:/Windows/Fonts/malgun.ttf"  # mac: /Library/Fonts/AppleGothic.ttf

    wc = WordCloud(
        font_path=font_path,
        background_color='white',
        width=800,
        height=600
    ).generate_from_frequencies(word_freq)

    wc.to_file(save_path)
4-4. 결과 화면(result) 함수에서 시각화 함수 호출

def result(request):
    if request.method == 'POST':
        keyword = request.POST['keyword']
        titles = collect_titles(keyword)
        results = []
        sentiments = []
        for t in titles:
            sentiment = get_sentiment(t)
            summary = summarize(t)
            results.append({'title': t, 'sentiment': sentiment, 'summary': summary})
            sentiments.append(sentiment)

        sentiment_path = os.path.join('static', 'images', 'sentiment.png')
        wordcloud_path = os.path.join('static', 'images', 'wordcloud.png')

        draw_sentiment_bar(sentiments, sentiment_path)
        generate_wordcloud([r['title'] for r in results], wordcloud_path)

        return render(request, 'analyzer/result.html', {
            'keyword': keyword,
            'results': results,
            'sentiment_img': sentiment_path,
            'wordcloud_img': wordcloud_path,
        })

5. result.html 수정 (이미지 삽입)


<h2>감성 분석 그래프</h2>
<img src="/{{ sentiment_img }}" alt="감성 그래프" width="500">

<h2>워드클라우드</h2>
<img src="/{{ wordcloud_img }}" alt="워드클라우드" width="500">

6. static 파일 설정 (개발용)

settings.py
STATIC_URL = '/static/'
config/urls.py 하단 추가

from django.conf import settings
from django.conf.urls.static import static

urlpatterns += static(settings.STATIC_URL, document_root=os.path.join(BASE_DIR, 'static'))

7. 실행 및 출력 예시

입력 키워드:
인공지능
결과 예시:
  • 감성 분석 표: 뉴스 제목, 감성 결과, 요약
  • 막대 그래프: 긍정 3 / 부정 4 / 중립 3
  • 워드클라우드: '미래', '기술', '사회', '위협', '자동화' 등이 시각적으로 강조됨

8. 마무리 요약

기능도구
감성 그래프Matplotlib + Counter
워드클라우드WordCloud + KoNLPy
이미지 삽입Django 템플릿에서 <img src="/static/...">