matplotlib绘制
Sometimes you want to see the number of registered users in your Django website over time. Fortunately Django stores the registration date of a user model instance in the date_joined field, so we can plot it.
有时您想查看一段时间内Django网站中已注册用户的数量。 幸运的是,Django将用户模型实例的注册日期存储在date_joined字段中,因此我们可以对其进行绘制。
先决条件 (Prerequisites)
You need an installation of numpy and matplotlib. You can install the libraries using pip:
您需要安装numpy和matplotlib 。 您可以使用pip安装库:
$ pip install numpy
$ pip install matplotlib
It is important that you install numpy before you install matplotlib, otherwise compiling the latter won’t work. You can also use your system package manager to install them instead, if you prefer that.
在安装matplotlib之前,请先安装numpy ,这一点很重要,否则编译后者将无法进行。 如果愿意,也可以使用系统软件包管理器来安装它们。
添加管理命令 (Adding a Management Command)
Now create a new Django management command. We could also do this as a standalone script, but by creating a management command we have easier access to the database.
现在创建一个新的Django管理命令。 我们也可以将其作为独立脚本来执行,但是通过创建管理命令,我们可以更轻松地访问数据库。
$ mkdir -p <myapp>/management/commands
$ touch <myapp>/management/__init__.py
$ touch <myapp>/management/commands/__init__.py
$ touch <myapp>/management/commands/plot_user_registrations.py
Now add the following code to your plot_user_registrations.py file:
现在,将以下代码添加到您的plot_user_registrations.py文件中:
from from optparse optparse import import make_option
make_option
from from django.core.management.base django.core.management.base import import BaseCommand
BaseCommand
from from django.contrib.auth django.contrib.auth import import get_user_model
get_user_model
import import numpy numpy as as np
np
import import matplotlib.pyplot matplotlib.pyplot as as plt
plt
from from matplotlib.dates matplotlib.dates import import date2num
date2num
class class CommandCommand (( BaseCommandBaseCommand ):
):
help help = = 'Plot user registrations. Use --save option to save the plot to a png file.'
'Plot user registrations. Use --save option to save the plot to a png file.'
option_list option_list = = BaseCommandBaseCommand .. option_list option_list + + (
(
make_optionmake_option (( '--save''--save' , , actionaction == 'store''store' ,
,
destdest == 'save''save' , , helphelp == 'Save the graph as a png to the specified location''Save the graph as a png to the specified location' ),
),
)
)
def def handlehandle (( selfself , , ** argsargs , , **** optionsoptions ):
):
# Get user join dates
# Get user join dates
User User = = get_user_modelget_user_model ()
()
datetimes datetimes = = UserUser .. objectsobjects .. values_listvalues_list (( 'date_joined''date_joined' , , flatflat == TrueTrue )
)
.. order_byorder_by (( 'date_joined''date_joined' )
)
dates dates = = mapmap (( lambda lambda dd : : dd .. datedate (), (), datetimesdatetimes )
)
# Get some auxilliary values
# Get some auxilliary values
min_date min_date = = date2numdate2num (( datesdates [[ 00 ])
])
max_date max_date = = date2numdate2num (( datesdates [[ -- 11 ])
])
days days = = max_date max_date - - min_date min_date + + 1
1
# Initialize X and Y axes
# Initialize X and Y axes
x x = = npnp .. arangearange (( min_datemin_date , , max_date max_date + + 11 )
)
y y = = npnp .. zeroszeros (( daysdays )
)
# Iterate over dates, increase registration array
# Iterate over dates, increase registration array
for for date date in in datesdates :
:
index index = = intint (( date2numdate2num (( datedate ) ) - - min_datemin_date )
)
yy [[ indexindex ] ] += += 1
1
y_sum y_sum = = npnp .. cumsumcumsum (( yy )
)
# Plot
# Plot
pltplt .. plot_dateplot_date (( xx , , y_sumy_sum , , xdatexdate == TrueTrue , , ydateydate == FalseFalse , , lsls == '-''-' , , msms == 00 , , colorcolor == '#16171E''#16171E' )
)
pltplt .. fill_betweenfill_between (( xx , , 00 , , y_sumy_sum , , facecolorfacecolor == '#D0F3FF''#D0F3FF' )
)
pltplt .. titletitle (( 'Registered Users''Registered Users' )
)
pltplt .. rcrc (( 'font''font' , , sizesize == 88 )
)
if if optionsoptions [[ 'save''save' ]:
]:
pltplt .. savefigsavefig (( optionsoptions [[ 'save''save' ])
])
elseelse :
:
pltplt .. showshow ()
()
用法 (Usage)
Now you can call your new management command:
现在,您可以调用新的管理命令:
$ python manage.py plot_user_registrations
This will open a new window containing the plot. You can also save it to a png file instead:
这将打开一个包含该图的新窗口。 您也可以将其保存为png文件:
$ python manage.py plot_user_registrations --save users.png
If you want, you can tweak the matplotlib configuration in order to change the plot style / colors / etc. If you find some nice improvements, feel free to leave a comment below!
如果需要,可以调整matplotlib配置,以更改打印样式/颜色/等。如果发现一些不错的改进,请随时在下面留下评论!
翻译自: https://www.pybloggers.com/2013/09/plot-registered-django-users-with-matplotlib/
matplotlib绘制