日期轴
可能的使用场景
当您从工作表数据创建图表并使用日期时,日期会沿图表中的水平(类别)轴绘制,并且Aspose.Cells会自动将类别轴更改为日期(时间刻度)轴。 日期轴以特定间隔或基本单位(例如天数、月份或年份)按年代顺序显示日期,即使工作表上的日期不是按顺序或基本单位相同。 默认情况下,Aspose.Cells会根据工作表数据中任意两个日期之间的最小差异确定日期轴的基本单位。例如,如果您拥有股价数据,日期之间的最小差异为七天,Excel会将基本单位设置为天数,但是如果您想要查看股票在较长时间内的表现,可以将基本单位更改为月份或年份。
处理日期轴就像处理Microsoft Excel一样
请参阅以下样本代码,创建一个新的Excel文件并在第一个工作表中放置图表的值。 然后,我们添加一个图表并设置Axis的类型 到TIME_SCALE,然后将基本单位设置为天数。
示例代码
from aspose.cells import Workbook | |
from aspose.cells.charts import CategoryType, ChartTextDirectionType, ChartType, TimeUnit | |
from aspose.cells.drawing import FillType | |
from datetime import datetime | |
# Create an instance of Workbook | |
workbook = Workbook() | |
# Get the first worksheet | |
worksheet = workbook.worksheets[0] | |
# Add the sample values to cells | |
worksheet.cells.get("A1").put_value("Date") | |
# 14 means datetime format | |
style = worksheet.cells.style | |
style.number = 14 | |
# Put values to cells for creating chart | |
worksheet.cells.get("A2").set_style(style) | |
worksheet.cells.get("A2").put_value(datetime(2022, 6, 26)) | |
worksheet.cells.get("A3").set_style(style) | |
worksheet.cells.get("A3").put_value(datetime(2022, 5, 22)) | |
worksheet.cells.get("A4").set_style(style) | |
worksheet.cells.get("A4").put_value(datetime(2022, 8, 3)) | |
worksheet.cells.get("B1").put_value("Price") | |
worksheet.cells.get("B2").put_value(40) | |
worksheet.cells.get("B3").put_value(50) | |
worksheet.cells.get("B4").put_value(60) | |
# Adda chart to the worksheet | |
chartIndex = worksheet.charts.add(ChartType.COLUMN, 9, 6, 21, 13) | |
# Access the instance of the newly added chart | |
chart = worksheet.charts[chartIndex] | |
# Add SeriesCollection (chart data source) to the chart ranging from "A1" cell to "B4" | |
chart.set_chart_data_range("A1:B4", True) | |
# Set the Axis type to Date time | |
chart.category_axis.category_type = CategoryType.TIME_SCALE | |
# Set the base unit for CategoryAxis to days | |
chart.category_axis.base_unit_scale = TimeUnit.DAYS | |
# Set the direction for the axis text to be vertical | |
chart.category_axis.tick_labels.direction_type = ChartTextDirectionType.VERTICAL | |
# Fill the PlotArea area with nothing | |
chart.plot_area.area.fill_format.fill_type = FillType.NONE | |
# Set max value of Y axis. | |
chart.value_axis.max_value = 70 | |
# Set major unit. | |
chart.value_axis.major_unit = 10.0 | |
# Save the file | |
workbook.save("DateAxis.xlsx") |