我正在尝试使用openpyxl创建折线图。两个轴应为time
和battery voltage
。使用openpyxl创建图表会将一个轴设置为电池电压,将另一个轴设置为行号。手动选择两列可使图表正确。打开创建图表的工作表会出现错误:“引用无效。标题,值或大小的引用必须是单个单元格,行,列。”
我不明白折线图如何只能使用一列或一行。我在这里做什么错了?
import os
import openpyxl
import re
from datetime import date, datetime, timedelta, time
os.chdir('C:\\Users\user\folder')
wb = openpyxl.load_workbook('file.xlsx')
wb.create_sheet('sheet2') # sheet where charts go
ws1 = wb['sheet1']
ws2 = wb['sheet2']
for cell in ws1['B:B']:
ws2.cell(row = cell.row, column = 1, value = cell.value)
for cell in ws1['D:D']:
ws2.cell(row = cell.row, column = 2, value = cell.value)
print('Creating charts...')
sheet = wb['sheet2'] # focus on sheet2 to pull data from/write chart to
refObj = openpyxl.chart.Reference(sheet, min_col=1, min_row=1, max_col=2, max_row=sheet.max_row)
seriesObj = openpyxl.chart.Series(refObj, title='Battery Voltage')
chartObj = openpyxl.chart.LineChart()
chartObj.title = 'Title'
chartObj.append(seriesObj)
sheet.add_chart(chartObj, 'C5')
wb.save('file.xlsx')
然后选择A列和B列并在Excel中创建折线图,将使我尝试获得该图表:
我对LineChart对象的论证是否错误?
编辑:
refObj = openpyxl.chart.Reference(sheet, min_col=2, min_row=2, max_col=2, max_row=sheet.max_row)
正确创建图形,但是将行号设置为x轴。我仍在尝试在x轴上获取时间。
答案 0 :(得分:0)
更仔细地阅读文档可以解决我的问题。这是制作带有正确格式的日期轴(对于我的应用程序)的折线图所需的代码:
.panel {
display: flex;
margin: auto;
width: 52%;
flex-direction: column;
justify-content: center;
padding: 5px;
border-style: solid;
border-color: black;
border-radius: 3px;
margin-bottom:5px;
background-color: #282936;
border: 1px solid #191921;
border-radius: 6px;
}