博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
matplotlib绘制_使用Matplotlib绘制已注册的Django用户
阅读量:2518 次
发布时间:2019-05-11

本文共 5105 字,大约阅读时间需要 17 分钟。

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字段中,因此我们可以对其进行绘制。

An example plot of user registrations.

先决条件 (Prerequisites)

You need an installation of and . You can install the libraries using pip:

您需要安装和 。 您可以使用pip安装库:

$ pip install numpy$ pip install matplotlib

It is important that you install before you install , otherwise compiling the latter won’t work. You can also use your system package manager to install them instead, if you prefer that.

在安装之前,请先安装 ,这一点很重要,否则编译后者将无法进行。 如果愿意,也可以使用系统软件包管理器来安装它们。

添加管理命令 (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 
/management/commands$ touch
/management/__init__.py$ touch
/management/commands/__init__.py$ touch
/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_optionmake_optionfrom from django.core.management.base django.core.management.base import import BaseCommandBaseCommandfrom from django.contrib.auth django.contrib.auth import import get_user_modelget_user_modelimport import numpy numpy as as npnpimport import matplotlib.pyplot matplotlib.pyplot as as pltpltfrom from matplotlib.dates matplotlib.dates import import date2numdate2numclass 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 configuration in order to change the plot style / colors / etc. If you find some nice improvements, feel free to leave a comment below!

如果需要,可以调整配置,以更改样式/颜色/等。如果发现一些不错的改进,请随时在下面留下评论!

翻译自:

matplotlib绘制

转载地址:http://xpqwd.baihongyu.com/

你可能感兴趣的文章
返回用户提交的图像工具类
查看>>
树链剖分 BZOJ3589 动态树
查看>>
挑战程序设计竞赛 P131 区间DP
查看>>
【例9.9】最长公共子序列
查看>>
NSFileManager打印目录下的文件的函数
查看>>
Rails--bundle exec rake db:migrate
查看>>
深度优先搜索 之 CODE[VS] 1116 四色问题
查看>>
浏览器渲染过程
查看>>
js遍历Object所有属性
查看>>
再也不学AJAX了!(三)跨域获取资源 ③ - WebSocket & postMessage
查看>>
pycharm设置python文件颜色
查看>>
不换行输出的两种方式
查看>>
贵在坚持不懈
查看>>
hdu 1251 统计难题
查看>>
java中关于String 类型数据 的存储方式
查看>>
javascript中的with语句
查看>>
常用设计模式:装饰者模式
查看>>
python接口自动化--get请求
查看>>
ajax 上传文件
查看>>
lintcode-easy-Flatten Binary Tree to Linked List
查看>>