首页 > 解决方案 > 使用日期值在 openpyxl 图表中设置 x 轴缩放

问题描述

当x轴的值是日期时,如何更改openpyxl中散点图x轴上的最小值/最大值?现在,我需要去掉图表左右两侧的大量填充。

如果我尝试chart.y_axis.scaling.min = date(2015, 9, 1),我会收到以下错误:

raise TypeError('expected ' + str(expected_type))
TypeError: expected <class 'float'>

理想情况下,最好设置一个选项来删除填充。第二个最佳选择是让 openpyxl 在最小/最大缩放参数中接受日期。

可重复的示例,每边都有一天的填充:

from datetime import date

from openpyxl import Workbook
from openpyxl.chart import (
    Reference,
    Series,
)
from openpyxl.chart import (
    ScatterChart,
)

wb = Workbook()
ws = wb.active

rows = [
    ['Date', 'Batch 1', 'Batch 2', 'Batch 3'],
    [date(2015, 9, 1), 40, 30, 25],
    [date(2015, 9, 2), 40, 25, 30],
    [date(2015, 9, 3), 50, 30, 45],
    [date(2015, 9, 4), 30, 25, 40],
    [date(2015, 9, 5), 25, 35, 30],
    [date(2015, 9, 6), 20, 40, 35],
]

for row in rows:
    ws.append(row)

chart = ScatterChart()
chart.title = "Line Chart"
chart.style = 13
chart.y_axis.title = 'Size'
chart.x_axis.title = 'Test Number'

x = Reference(ws, min_col=1, min_row=2, max_row=7)
y = Reference(ws, min_col=2, min_row=1, max_row=7)
s1 = Series(y, xvalues=x, title_from_data=True)
chart.append(s1)
chart.style = 13
# chart.y_axis.scaling.min = date(2015, 9, 1)

ws.add_chart(chart, "A10")

wb.save("/tmp/line.xlsx")

在此处输入图像描述

在我的实际用例中,我有一年多的数据,每边都有大约一个月的填充。

标签: chartsopenpyxl

解决方案


推荐阅读