areski / django-nvd3

Django wrapper for nvd3 - It's time for beautiful charts
Other
417 stars 124 forks source link

How to Use X-Axis Dates #48

Open akrf opened 9 years ago

akrf commented 9 years ago

I am attempting to use django-nvd3 to create a simple line chart with dates on the X axis and integers on the Y axis. At first I was using actual datetime objects for the X axis data, but that resulted in "not JSON serializable" errors, so now I'm using string representations of dates. The chart code in my view looks liket this:

    xdata = ['2015-01-01',
             '2015-02-01',
             '2015-03-01',
             ]
    ydata = [10, 20, 40]
    ydata2 = [8, 4, 14]

    chartdata = {
            'x': xdata,
            'name1': 'series 1', 'y1': ydata,
            'name2': 'series 2', 'y2': ydata2,
            }

    context['chart'] = {
        'type': "lineChart",
        'container': 'chart_container',
        'data': chartdata,
        'extra': {
            'x_is_date': True,
            'tag_script_js': True,
            'jquery_on_ready': False,
        }
    }

This results in a chart with the proper Y axis. However, I see no lines and the X axis is labelled "31 Dec 1969, 31 Dec 1969, 31 Dec 1969".

How am I supposed to specify that the contents of xdata are string representations of dates?

mboelen commented 9 years ago

Same issue. The documentation could benefit from using "fixed" dummy data, instead of random generated data.

aaronvanderlip commented 7 years ago

Here is a solution.

You need to pass a value that the JavaScript Date object can use. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

I chose

value Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC, with leap seconds ignored (Unix Epoch; but consider that most Unix time stamp functions count in seconds).

As it seems the most reliable.

Now you need to prepare your data. A quick example would be:

import datetime, calendar

date = datetime.datetime.now()

# need to convert the datetime object to seconds from Unix Epoch
date = calendar.timegm(date.timetuple)

# then convert to milliesonds

date = date * 1000

I hope this helps someone.

Nicolas-Prinsloo commented 5 years ago

I hope this helps someone.

This helped me solve a problem that I've been sitting on for hours. Lifesaver, thank you @aaronvanderlip

bossajie commented 5 years ago

what data are the examples for the date? @Nicolas-Prinsloo and @aaronvanderlip