import xlsxwriter
# Create a new Excel workbook and add a worksheet
workbook = xlsxwriter.Workbook('chart_with_trendline.xlsx')
worksheet = workbook.add_worksheet()
# Sample data
x_data = [1, 2, 3, 4, 5, 6, 7] # Adding more values to x_data
y_data = [5, 4, 3, 2, 1, 2, 3] # Adding more values to y_data
gearChange = 2 #index 2
line_x_data = []
line_y_data = []
line_x_data.append(x_data[gearChange])
line_y_data.append(y_data[gearChange])
line_x_data.append(x_data[gearChange])
line_y_data.append(0)
# Write data to the worksheet
worksheet.write_column('A1', x_data)
worksheet.write_column('B1', y_data)
# Write line data to worksheet
worksheet.write_column('C1', line_x_data)
worksheet.write_column('D1', line_y_data)
# Add a chart object
chart = workbook.add_chart({'type': 'scatter'})
# Add scatter series to the chart
chart.add_series({
'name': 'Y1',
'categories': '=Sheet1!$A$1:$A$7',
'values': '=Sheet1!$B$1:$B$7',
'marker': {'type': 'circle'}
})
# Add line series to the chart
chart.add_series({
'categories': '=Sheet1!$C$1:$C$2', # Adjusted for new data range
'values': '=Sheet1!$D$1:$D$2', # Adjusted for new data range
'line': {'type': 'linear'} # Adding linear trendline
})
# Set chart title and axis labels
chart.set_title({'name': 'Chart With Trendline'})
chart.set_x_axis({'name': 'X Axis'})
chart.set_y_axis({'name': 'Y Axis'})
# Insert the chart into the worksheet
worksheet.insert_chart('E2', chart)
# Close the workbook
workbook.close()
这是我目前的代码。我想将值 3 添加到 X 轴,因为这是我绘制的线的 X 截距。我浏览了文档,似乎找不到任何允许我执行此操作的函数。我也问过 ChatGPT,但没有运气。如果有更好的方法在特定的换档点绘制垂直线,那也很棒,因为我已经在这方面坚持了几天(更大项目的一部分)。任何帮助将非常感激。
我尝试更改线路:
chart.set_x_axis({'name': 'X Axis'})
所以它看起来像这样:
chart.set_x_axis({'name': 'X Axis', 'major_tick_values': line_x_data})
为了在X轴上得到3但没有成功。
只需将主单位设置为 1,以便轴以 1 秒计数 1 -8。
添加到x轴设置
chart.set_x_axis({'name': 'X Axis'})
chart.set_x_axis({
'name': 'X Axis',
'major_unit': 1, # set major unit to 1
})