Echarts 是百度开源的一个数据可视化 JS 库,主要用于数据可视化。pyecharts 是一个用于生成 Echarts 图表的类库。实际上就是 Echarts 与 Python 的对接。
本次使用django2.0 和 pyecharts0.3.3
1. setttins.py 添加自己创建的app名称,和静态文件的路径
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_report', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'devdb', 'USER': 'hysh', 'PASSWORD': 'hysh', 'HOST': '192.168.191.3', 'PORT': '1521', } } STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), )
2.urls.py
from django.contrib import admin from django.urls import path from month_report import views urlpatterns = [ path('admin/', admin.site.urls), path('guo/', views.guo_report, name='index'), ]
3.views.py
from django.shortcuts import render from django.db import connection from django.http import HttpResponse from django.template import loader from pyecharts import Bar, Geo def exc_sql(sql): cursor = connection.cursor() cursor.execute(sql) result = cursor.fetchall() return result def guo_report(request): # select province, difi_re_num from REPORT_REG ret = """select city, difi_re_num from REPORT_REG a, province_to_city b where a.province=b.province""" data_list = exc_sql(ret) attr = [i[0] for i in data_list] value = [i[1] for i in data_list] geo = Geo("全国各地用户注册图", width=1200, height=600) geo.add("各省注册量", attr, value, type="effectScatter", border_color="#ffffff", symbol_size=2, is_label_show=True, label_text_color="#00FF00", label_pos="inside", symbol_color="yellow", geo_normal_color="#006edd", geo_emphasis_color="#0000ff") data = {'data': geo.render_embed()} return render(request, 'guo_report.html', data)
4.guo_report.html
<!-- myfirstvis/templates/myfirstvis/pyecharts.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>MY-ECharts</title> <script src="http://oog4yfyu0.bkt.clouddn.com/echarts.min.js"></script> <script src="http://oog4yfyu0.bkt.clouddn.com/echarts-gl.js"></script> <script type="text/javascript " src="http://echarts.baidu.com/gallery/vendors/echarts/map/js/china.js"></script> <script type="text/javascript " src="http://echarts.baidu.com/gallery/vendors/echarts/map/js/world.js"></script> <script type="text/javascript " src="http://oog4yfyu0.bkt.clouddn.com/wordcloud.js"></script> </head> <body> {{data|safe}} </body> </html>
效果图: