python---图表的使用

时间:2023-03-09 23:04:20
python---图表的使用

一:使用预览

python---图表的使用

二:插件使用来源

Highcharts(本次使用)

ECharts

三:插件的使用

HighCharts的简单上手

(一)后台传递数据

getHchart方法获取用户数据(用户名,数据列表)

    def getHchart(self):
user_list = models.User.objects.filter()
user_data = []
for user in user_list:
cursor = connections['default'].cursor()
       #在数据库语句中使用字符串格式化需要两个%%,在python语言中使用一个%
cursor.execute("""select strftime('%%s',strftime("%%Y-%%m-",ptime))*1000,count(id) from repository_trouble where processer_id = %s GROUP BY strftime("%%Y-%%m",ptime)""",[user.nid])
result = cursor.fetchall() #数据列表
user_data.append({
'name':user.username,
'data':result
})
return user_data

数据格式:

[
{'name': '山上有风景', 'data': [(, ), (, ), (, )]},
{'name': '宁静致远', 'data': [(, ), (, ), (, ), (, )]},
{'name': '蜡笔小新', 'data': []},
{'name': '你大爷', 'data': []},
{'name': '但是', 'data': []}
]

(二)将数据Json化,传递到前端后的处理方法

.导入js文件
<script src="/static/plugins/Highcharts-6.1.0/code/highcharts.js"></script>
.创建一个DOM容器
<div id="container" style="min-width:400px;height:400px"></div>
.图表配置
<script>
var chart = null; Highcharts.setOptions({
global:{
useUTC:false
}
}) config = {
chart: {
type: 'spline'  #设置图表类型
},
title: {
text: '报障数据统计'  #标题设置
},
subtitle: {
text: '数据来源: 127.0.0.1(来源本地)'  #子标题
},
xAxis: {  #X轴配置
type:"datetime",
dateTimeLabelFormats:{
year:"%Y",
month:"%Y-%m",
},
title:{
text:null
}
},
yAxis: {  #Y轴配置
title: {
text: '报障数量'
}
},
credits:{  #版权
enabled: false // 禁用版权信息
},
plotOptions: {  
line: {
dataLabels: {
enabled: true // 开启数据标签
},
enableMouseTracking: false // 关闭鼠标跟踪,对应的提示框、点击事件会失效
}
},
} $(function(){
$.ajax({
url:"/backend/trouble-hchart.html",
type:"POST",
data:{'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType:"json",
success:function(data){
config['series']=data
chart = Highcharts.chart('container', config);  #设置图表的数据
}
})
}) </script>