[Django]Canvasjs으로 멀티 라인차트(Line Chart) 보여주기(feat.무료)

2021. 1. 2. 03:44python 전문가로/Django

반응형

위와같이 Django 웹페이지에서 차트를 띄우는 방법을 공유드리고자 합니다! 

차트는 오픈소스인 canvasjs를 사용했습니다. 

 

canvasjs.com/ ◀canvasjs 홈페이지에 들어가면 다양한 Demo가 있으니 한번 확인해보세요~! 

 

Beautiful HTML5 Charts & Graphs | 10x Fast | Simple API

HTML5 JavaScript Charts built on top of HTML5 Canvas Element. Renders across devices & is 10x faster than JavaScript Charting libraries based on SVG.

canvasjs.com

 

무료 차트 플러그인 중에서 canvasjs, hichart 등 몇가지 있지만 제가 canvasjs를 고른 이유는 .. 별거없습니다..

"예.뻐.서." ㅋㅋㅋㅋ

먼저 Django홈페이지를 로컬(http://127.0.0.1:8000/)로 띄우신 분들 한해서 설명할게요! (로컬 홈페이지 띄우는 법도 곧 올리도록 하겠습니다!)

DB는 Django에서 기본적으로는 SQLite을 사용하도록 구성되어 있습니다.

 SQLite는 Python에서 기본으로 제공되기 때문에 별도로 설치할 필요가 없습니다! (DB연동 진짜 쉬워요)

방대한 서비스를 하고싶으시다면 SQLite는 조금 무리가 있겠죠?

DB관련된 내용은 아래 링크에서 확인 부탁드려요~!

shiningyouandme.tistory.com/16

 

[Django]장고 기본 DB(SQLite)를 활용하여 연동하기

안녕하세요! 웹페이지 프레임워크로 Django를 선택한 당시는 위너! ㅎㅎ 아마 Python 언어때문에 Django 프레임워크를 선택하셨을거에요 맞죠? (아님 말구..) 저는 Python언어를 활용해서 웹페이지까지

shiningyouandme.tistory.com

 

먼저 canvasjs.com가서 demo를 클릭해서 사용하려는 차트를 고릅니다!

그럼 다양한 차트 카테고리가 왼쪽에 보입니다!

저는 Line Chart Multiple Axes를 사용할거에요!

원하는 차트의 카트를 클릭하면 친절하게 예시와 예시코드화면이 나와요!

저 샘플코드는 직접 바로 수정하여 상태를 볼 수 있어서 편리했어요.

바로 코드 수정해서 적용된 차트가 변형되어서 도움이 컸습니다. 

여기 제시되어있는 예시 코드를 참고해서 django에 넣어보겠습니다!

 

 

먼저 DB과 연결된 models.py입니다. 

class Movevixlibor(models.Model):
    id = models.AutoField(primary_key=True)
    date = models.CharField(max_length=30)
    move = models.FloatField()
    vix = models.FloatField()
    libor = models.FloatField()

 

그리고 models.py에서 html로 데이터를 뿌려주는 것을 연결해주는 veiws.py입니다.

from board.models import *
from django.http import HttpResponse, HttpResponseRedirect
import pandas as pd
import matplotlib.pyplot as plt
import json
from django.core.serializers.json import DjangoJSONEncoder
from datetime import datetime

def index(request):
    movevixlibor = Movevixlibor.objects.values()
    movevixlibor_json = json.dumps(list(movevixlibor), cls=DjangoJSONEncoder)
    
    context = {
    #html로 보내는 필드명을 ''(따옴표)안에 넣어주면 됩니다.
    'movevixlibor_json': movevixlibor_json,
    }
 
 
##html로 값을 보내는 부분    
    return render(request, 'board/index.html', context)

views.py에서 데이터에서 html로 render함수를 이용해서 보냈습니다.

render함수를 이용해서 데이터를 html로 보냈어요!

index.html입니다. 

{% load static %}
<!DOCTYPE HTML>

<html>
<head>
    <meta charset="UTF-8">
	<title></title>
 	<meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <link rel="stylesheet" href='{% static "board/bootstrap/bootstrap.css" %}' media="screen">
    <link rel="stylesheet" href='{% static "board/_assets/css/custom.min.css" %}'>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <!-canvasjs 플러그인--->
    <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

</head>
<body>
	<div id="market_chart" class="col-lg-12" style="height: 180px;  margin-top:-15px; "></div>
<!--universe chart-->
	<script type="text/javascript" src='{% static "board/main_tab_charts/main/universe_chart.js" %}'></script>
</body>
</html>

html에서는 몇가지 작업을 더 해줘야 하는데요.

①canvasjs 플러그인 해주기(라이센스를 샀다면, 안샀으면 안하셔도 됩니다. 다만 차트에 워터마크가 찍혀 나옵니다.)

②body끝나기 전에 html과 javascript를 연결해주는 javascript 경로 코드를 작성해줘야합니다. 

<script type="text/javascript" src='{% static "board/main_tab_charts/main/universe_chart.js" %}'></script>

 

이제 차트를 표현하는 universe_chart.js(javascript)입니다.

$(function () {
    const movevixlibor = document.getElementById("movevixlibor").value;
    const movevixlibor_json = JSON.parse(movevixlibor);
    
    var dataPoint_move = [];
    for (var i = 0; i < movevixlibor_json.length; i++) {
        dataPoint_move.push({
            x: new Date(movevixlibor_json[i].date),
            y: parseFloat(movevixlibor_json[i].move)
        });
    }


    var dataPoint_vix = [];
    for (var i = 0; i < movevixlibor_json.length; i++) {
        dataPoint_vix.push({
            x: new Date(movevixlibor_json[i].date),
            y: parseFloat(movevixlibor_json[i].vix)
        });
    }


    var dataPoint_libor = [];
    for (var i = 0; i < movevixlibor_json.length; i++) {
        dataPoint_libor.push({
            x: new Date(movevixlibor_json[i].date),
            y: parseFloat(movevixlibor_json[i].libor)
        });
    }
    
    
    
    var market_chart = new CanvasJS.Chart("market_chart", {
        animationEnabled: true,
        theme: "dark2",
        title:{
            text: "Volatility Index",
            fontSize:13,
        },
        	zoomEnabled:true,
        toolTip: {
            enabled: true,       
            animationEnabled: true 
        },
        legend: {
            cursor: "pointer",
            horizontalAlign: "left", // "center" , "right"
            verticalAlign: "top",
            dockInsidePlotArea: false,
        },
        axisX:{
            crosshair: {
                enabled: true
            }
        },
        axisY: {
            title:"비율",
            includeZero: false,
            gridColor:"white",
            gridThickness: 0.3,
            gridDashType: "dot",

        },
        axisY2: {
            title:"US",
            includeZero: false,
            gridColor:"white",
            gridThickness: 0.3,
            gridDashType: "dot",

        },
        backgroundColor : "rgb(43,62,80)",
        data: [
            {
                name:"MOVE",
                showInLegend: true,
                axisYType: "secondary",
                markerType: "none",
                type: "spline",
                indexLabelFontSize: 16,
                //데이터 넣는 곳
                dataPoints: dataPoint_move
            },

            {
                name:"VIX",
                showInLegend: true,
                axisYType: "secondary",
                markerType: "none",
                type: "spline",
                indexLabelFontSize: 16,
                //데이터 넣는 곳
                dataPoints: dataPoint_vix
            },

            {
                name:"LIBOR",
                showInLegend: true,
                markerType: "none",
                type: "spline",
                indexLabelFontSize: 16,
                //데이터 넣는 곳
                dataPoints:dataPoint_libor
            },


        ]
    });


    market_chart.render();


});
    

javascript에서 사용할 데이터를 가져올때 json 형식으로 데이터를 가져옵니다. 

const movevixlibor = document.getElementById("movevixlibor").value;
const movevixlibor_json = JSON.parse(movevixlibor);

json데이터를 list에 담아줍니다. 하나의 column만 사용하기 때문에 for문을 사용해서 list에 담아줍니다.

var dataPoint_move = [];
for (var i = 0; i < movevixlibor_json.length; i++) {

dataPoint_move.push({
x: new Date(movevixlibor_json[i].date),
y: parseFloat(movevixlibor_json[i].move)

});
}

차트 함수의 dataPoints 부분에 list를 적어주면 됩니다~! 

그리고 저는 꺽는 부분에 꼭지점이 없는게 더 예뻐보이더라구요!

그래서 markerType: "none" 이런 옵션을 주면 되어요~

이런 옵션들은 canvasjs document가 있어서 아래 링크 에서 다양한 옵션들이 있어서 옵션을 추가하면서 차트를 커스터마이즈를 할 수 있습니다.

canvasjs.com/docs/charts/basics-of-creating-html5-chart/

 

Tutorial on Creating Charts | CanvasJS JavaScript Charts

An interactive tutorial on creating HTML5 JavaScript Charts using CanvasJS.

canvasjs.com