In the previous article, pyecharts realizes the visualization of movie data analysis and has realized the visualization of pyecharts. This article mainly implements Django combined with pyecharts to make a small visual website/system.
I wrote it with Sublime Text on the Centos7 virtual machine, you can do whatever you want.
Article directory
Create a python virtual environment
I am using Python 3.6.8, as long as you are not Python2 or older, it should work fine.
Go to the directory where you store the python virtual environment, mine is/home/xwk/Desktop/python_vens
[xwk@forpython ~]$ cd Desktop/python_vens/
[xwk@forpython python_vens]$ pwd
/home/xwk/Desktop/python_vens
[xwk@forpython python_vens]$ python3 -V
Python 3.6.8
Create a books
python virtual environment called
[xwk@forpython python_vens]$ python3 -m venv books
What should I do if I find that I created the wrong name? The movie visualization I made should be created. movies
If you have installed the pip library and don’t want to reinstall it one by one, execute
导出已安装的pip库的名称及版本
pip freeze > requirements.txt
重新创建好虚拟环境后,根据导出的库的名称及版本重新安装
pip install -r requirements.txt
To delete the created wrong environment, just delete the virtual environment directory books, be careful not to delete the wrong one.
[xwk@forpython python_vens]$ rm -rf books/
Recreate movies
the virtual environment named
[xwk@forpython python_vens]$ python3 -m venv movies
Enter the virtual environment
[xwk@forpython python_vens]$ cd movies/
[xwk@forpython movies]$ source ./bin/activate
(movies) [xwk@forpython movies]$
Exit the virtual environment
(movies) [xwk@forpython movies]$ deactivate
[xwk@forpython movies]$
This is just a demonstration, how to enter and exit the virtual environment, the code needs to enter the virtual environment to run.
Re-enter the virtual environment
[xwk@forpython movies]$ source ./bin/activate
(movies) [xwk@forpython movies]$
Install the required python library
pip install django
pip install pyecharts
pip install pandas
pip install pymysql
pip should automatically install the relevant dependent packages, check the installed packages
(movies) [xwk@forpython movies]$ pip list
Different versions of libraries may have different codes. For example, Django, if you are not the above version, if there is an error in the code, you can search and modify it yourself. This is not difficult, because you are definitely not the only one who has encountered similar problems.
Create a Django project
Go to the directory where you store the python virtual environment, mine is/home/xwk/Desktop/python_projects
(movies) [xwk@forpython movies]$ cd /home/xwk/Desktop/python_projects
(movies) [xwk@forpython python_projects]$
Create a Django project called movies
django-admin startproject movies
(movies) [xwk@forpython python_projects]$ cd movies/
(movies) [xwk@forpython movies]$ ls
manage.py movies
Configure the mysql database, you can create a named database according to your needs movies
. This article mainly uses pandas, and mysql is only needed by django. You can also import csv files into mysql, and use sql statements to query.
mysql> create database movies;
Query OK, 1 row affected (0.00 sec)
(movies) [xwk@forpython movies]$ pwd
/home/xwk/Desktop/python_projects/movies/movies
(movies) [xwk@forpython movies]$ ls
asgi.py __init__.py __pycache__ settings.py urls.py wsgi.py
Configure the files in this directory settings.py
and change DATABASES
the content to:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'movies',
'USER': 'root',
'PASSWORD': 'root',
'HOST': 'localhost',
'PORT': '3306',
}
}
__init__.py
Add to this directory
import pymysql
pymysql.install_as_MySQLdb()
Create a Django application
Create a movies_pyecharts
Django application named
Go to this directory
(movies) [xwk@forpython movies]$ pwd
/home/xwk/Desktop/python_projects/movies
(movies) [xwk@forpython movies]$ ls
manage.py movies
(movies) [xwk@forpython movies]$ python ./manage.py startapp movies_pyecharts
(movies) [xwk@forpython movies]$ cd movies
(movies) [xwk@forpython movies]$ ls
asgi.py __init__.py __pycache__ settings.py urls.py wsgi.py
Edit settings.py
the file
to add to INSTALLED_APPS'movies_pyecharts',
(movies) [xwk@forpython movies]$ cd ../movies_pyecharts/
(movies) [xwk@forpython movies_pyecharts]$ ls
admin.py __init__.py models.py tests.py
apps.py migrations templates views.py
Edit (or create new if not) urls.py
file
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
]
(movies) [xwk@forpython movies_pyecharts]$ cd ../movies
(movies) [xwk@forpython movies]$ ls
asgi.py __init__.py __pycache__ settings.py urls.py wsgi.py
Edit urls.py
(note the directory switch)
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('movies_pyecharts/', include('movies_pyecharts.urls')),
]
movies_pyecharts
First create a new templates
folder under the folder
and place the pyecharts template in pyecharts.render.templates for specific location reference ( /home/xwk/Desktop/python_vens/movies/lib/python3.6/site-packages/pyecharts/render/templates
)
Copy to the newly created templates folder
and copy the obtained data files to movies_pyecharts
the folder
first visual page
edit movies_pyecharts/views.py
from jinja2 import Environment, FileSystemLoader
from pyecharts.globals import CurrentConfig
from django.http import HttpResponse
CurrentConfig.GLOBAL_ENV = Environment(loader=FileSystemLoader("./movies_pyecharts/templates"))
import pandas as pd
from pyecharts.charts import Bar,Pie,Line
import pyecharts.options as opts
data=pd.read_csv('./movies_pyecharts/电影.csv')
Year=data['上映年份'].value_counts().reset_index()
Year.rename(columns={
"index":"上映年份","上映年份":"电影数量"},inplace=True)
def index(request):
bar = (
Bar(init_opts=opts.InitOpts(height='700px', theme='light'))
.add_xaxis(
Year['上映年份'].tolist()[::-1])
.add_yaxis(
"电影数量",
Year['电影数量'].tolist()[::-1],
label_opts=opts.LabelOpts(is_show=False),
)
.set_series_opts(itemstyle_opts=opts.ItemStyleOpts(
border_color='#5C3719', ))
.set_global_opts(
title_opts=opts.TitleOpts(
title='上映年份及电影数量',
subtitle='截止2023年3月',
title_textstyle_opts=opts.TextStyleOpts(
font_family='Microsoft YaHei',
font_weight='bold',
font_size=22,
),
pos_top='1%'),
legend_opts=opts.LegendOpts(is_show=True),
xaxis_opts=opts.AxisOpts(
# name='电影数量',
is_show=True,
max_=int(Year['电影数量'].max()),
axislabel_opts=opts.LabelOpts(
font_family='Microsoft YaHei',
font_weight='bold',
font_size='14' #标签文本大小
)),
yaxis_opts=opts.AxisOpts(
# name='上映年份',
is_show=True,
axislabel_opts=opts.LabelOpts(
#interval=0,#强制显示所有y轴标签,需要可以加上
font_family='Microsoft YaHei',
font_weight='bold',
font_size='14' #标签文本大小
)),
tooltip_opts=opts.TooltipOpts(
is_show=True,
trigger='axis',
trigger_on='mousemove|clike',
axis_pointer_type='shadow',
),
toolbox_opts=opts.ToolboxOpts(is_show=True,
pos_left="right",
pos_top="center",
feature={
"saveAsImage":{
}}
)
).reversal_axis())
return HttpResponse(bar.render_embed())
Open it now http://127.0.0.1:8000/movies_pyecharts/
, and you can see the graph!
It's just a page and I try to add pages.
Add more visualization pages
editmovies_pyecharts/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index,name='index'),
path('director/',views.director,name='director'),
]
Add the following code to movies_pyecharts/views.py :
def director(request):
Director = data['导演'].value_counts()[0:11].reset_index()
Director.rename(columns={
"index": "导演", "导演": "电影数量"}, inplace=True)
pie = (
Pie(init_opts=opts.InitOpts(theme='light'))
.add(
series_name='电影类型',
data_pair=[list(z) for z in zip(
Director['导演'].to_list(), Director['电影数量'].to_list())],
radius=["40%", "75%"],
)
# .set_colors(["blue", "green", "yellow", "red", "pink", "orange", "purple"])
.set_global_opts(
title_opts=opts.TitleOpts(
title="导演及电影数量",
subtitle='TOP10',
title_textstyle_opts=opts.TextStyleOpts(
font_family='Microsoft YaHei',
font_weight='bold',
font_size=22,
),
),
legend_opts=opts.LegendOpts(
pos_left="left",
pos_top="center",
orient='vertical',
is_show=True
),
toolbox_opts=opts.ToolboxOpts(
is_show=True,
pos_left="right",
pos_top="center",
feature={
"saveAsImage": {
}}
)
)
.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
)
return HttpResponse(pie.render_embed())
That's it for the Open http://127.0.0.1:8000/movies_pyecharts/director/
Add More Pages method, I won't add any more.
If you want to change the title of the page,
change the code similar to the following
Bar(init_opts=opts.InitOpts(height='700px', theme='light',page_title ='上映年份及电影数量'))
For more configuration, refer to pyecharts official website documentation
. Django is very powerful. The visualization I made is just an introduction.