使用python绘制CSV文件的数据

v09wglhw  于 2023-01-06  发布在  Python
关注(0)|答案(1)|浏览(128)

我有一个带有一些数据的csv文件,我想使用python代码绘制这些数据的图形,并且我想将绘图保存在同一个csv文件中。
我就是这样插入数据的

import csv
 
list=[5,6,7,5,8]              
csv_file='path/csv_file.csv'       
outfile = open(csv_file,'w')
out = csv.writer(outfile)
list.insert(0,'header1')
out.writerows([list])
outfile.close()

我想绘制此数据并将图插入csv文件

2nbm6dog

2nbm6dog1#

如果你想把数据保存到excel文件并插入图像,你应该看看openpyxl模块,它允许你编写和编辑excel文件。
你可以用matplotlib来生成你的图像,假设你有一个变量来保存你的数据(这里我用示例值填充了它),注意你不应该把你的变量叫做list,因为这是Python中创建列表的内置函数的名字,你会覆盖它,所以我在这里把它叫做l

l = [0, 1, 2, 3, 4, 5]

现在可以使用matplotlib绘制数据。

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(l) # x-values are automatically added

然后,您可以使用io.BytesIO设置一个buffer对象并写入该对象,而不是将图形保存到图像文件中,从而有效地将图像保存在内存中。

from io import BytesIO
buffer = BytesIO()
fig.savefig(buffer, format='png', dpi=100) # Choose dpi as you like
buffer.seek(0) # Go back to beginning of the buffer

现在,使用openpyxl创建一个excel文件,并填写值和图像。

import openpyxl
wb = openpyxl.Workbook()
ws =  wb.active
header = 'Column 1' # Replace here

# Write header to first cell
ws.cell(row=1, column=1).value = header

# Fill cells with your list values
for i in range(len(l)):
    ws.cell(row=i+2, column=1).value = l[i]
    
# Load the image from buffer to openpyxl and write it
img = openpyxl.drawing.image.Image(buffer)
img.anchor = 'C3' # Cell at which the upper left corner of the figure is placed
ws.add_image(img)

# Save to excel file
wb.save(filename='data.xlsx') # Here you can give a full filepath if you want

相关问题