matplotlib绘制_使用Matplotlib绘制已注册的Django用户

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 numpy and matplotlib. You can install the libraries using pip:

您需要安装numpymatplotlib 。 您可以使用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绘制

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值