使用Django模板绘制Google图表(组合图)可以通过以下步骤实现:
pip install django
pip install googlecharts
from django.shortcuts import render
from googlecharts import Chart
def chart_view(request):
# 生成图表数据
data = [
['Year', 'Sales', 'Expenses'],
['2018', 1000, 400],
['2019', 1170, 460],
['2020', 660, 1120],
['2021', 1030, 540]
]
# 创建组合图对象
chart = Chart("ComboChart", "chart_div")
# 设置图表数据
chart.data(data)
# 设置图表选项
chart.options({
'title': 'Sales and Expenses',
'hAxis': {'title': 'Year'},
'vAxis': {'title': 'Amount'},
'seriesType': 'bars',
'series': {1: {'type': 'line'}}
})
# 渲染图表模板并传递图表对象
return render(request, 'chart.html', {'chart': chart})
<!DOCTYPE html>
<html>
<head>
<title>Google Chart</title>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable({{ chart.data_json|safe }});
var options = {{ chart.options_json|safe }};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 100%; height: 400px;"></div>
</body>
</html>
from django.urls import path
from .views import chart_view
urlpatterns = [
path('chart/', chart_view, name='chart'),
]
现在,当访问/chart/
URL时,将会显示一个包含Google组合图的页面。该图表将根据视图函数中生成的数据进行绘制。
推荐的腾讯云相关产品:腾讯云云服务器(https://cloud.tencent.com/product/cvm)和腾讯云数据库MySQL版(https://cloud.tencent.com/product/cdb_mysql)可以用于支持Django应用的部署和数据存储。
领取专属 10元无门槛券
手把手带您无忧上云