File: chart_date_axis.py

package info (click to toggle)
xlsxwriter 3.1.9-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 56,308 kB
  • sloc: python: 51,511; javascript: 7,768; sh: 284; makefile: 195; perl: 75
file content (65 lines) | stat: -rw-r--r-- 1,536 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#######################################################################
#
# An example of creating an Excel charts with a date axis using
# Python and XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright 2013-2023, John McNamara, jmcnamara@cpan.org
#

from datetime import date
import xlsxwriter

workbook = xlsxwriter.Workbook("chart_date_axis.xlsx")

worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "line"})
date_format = workbook.add_format({"num_format": "dd/mm/yyyy"})

# Widen the first column to display the dates.
worksheet.set_column("A:A", 12)

# Some data to be plotted in the worksheet.
dates = [
    date(2013, 1, 1),
    date(2013, 1, 2),
    date(2013, 1, 3),
    date(2013, 1, 4),
    date(2013, 1, 5),
    date(2013, 1, 6),
    date(2013, 1, 7),
    date(2013, 1, 8),
    date(2013, 1, 9),
    date(2013, 1, 10),
]

values = [10, 30, 20, 40, 20, 60, 50, 40, 30, 30]

# Write the date to the worksheet.
worksheet.write_column("A1", dates, date_format)
worksheet.write_column("B1", values)

# Add a series to the chart.
chart.add_series(
    {
        "categories": "=Sheet1!$A$1:$A$10",
        "values": "=Sheet1!$B$1:$B$10",
    }
)

# Configure the X axis as a Date axis and set the max and min limits.
chart.set_x_axis(
    {
        "date_axis": True,
        "min": date(2013, 1, 2),
        "max": date(2013, 1, 9),
    }
)

# Turn off the legend.
chart.set_legend({"none": True})

# Insert the chart into the worksheet.
worksheet.insert_chart("D2", chart)

workbook.close()