我正在尝试编写一个从 Excel 生成一系列图表的 Python 脚本。 Excel文件有每天不同汽车的价格。
第 1 列是日期;第2栏是绿色汽车的价格;第 3 列是红色汽车的价格等。以下代码仅输出第一列和最后一列的图表(第一列是汽车价格,而不是日期列),并且两个图表是分开的。例如,第一个图表显示在 D 列中,第二个图表显示在 AFD 列中。
如何修改我的代码,使其以漂亮的网格格式显示(每行两个图表)?
import pandas as pd
import matplotlib.pyplot as plt
import xlsxwriter
import io
def generate_seasonal_charts(file_path, start_date, end_date, output_file):
df = pd.read_excel(file_path)
df['Date'] = pd.to_datetime(df['Date'])
df = df[(df['Date'] >= start_date) & (df['Date'] <= end_date)]
df.set_index('Date', inplace=True)
workbook = xlsxwriter.Workbook(output_file)
worksheet = workbook.add_worksheet()
# Define image dimensions and positions
image_width = 800
image_height = 400
x_offset = 0
y_offset = 0
y_spacing = image_height + 20
# Create charts for each column
for i, column in enumerate(df.columns[1:]):
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(df.index, df[column])
ax.set_xlabel('Date')
ax.set_ylabel('Value')
ax.set_title(f'Seasonal Data for {column}')
plt.grid(True)
# Save the plot to a buffer
buf = io.BytesIO()
fig.savefig(buf, format='png')
buf.seek(0)
# Embed the image in the Excel worksheet
if i == 0:
worksheet.insert_image(x_offset, y_offset, f"Chart {i+1}", {'image_data': buf, 'x_scale': image_width / fig.canvas.get_width_height()[0], 'y_scale': image_height / fig.canvas.get_width_height()[1]})
else:
y_offset += y_spacing
worksheet.insert_image(x_offset, y_offset, f"Chart {i+1}", {'image_data': buf, 'x_scale': image_width / fig.canvas.get_width_height()[0], 'y_scale': image_height / fig.canvas.get_width_height()[1]})
plt.close(fig)
workbook.close()
file_path = "chart testing.xlsx"
output_file = "output.xlsx"
start_date = '2018-01-01'
end_date = '2023-12-31'
generate_seasonal_charts(file_path, start_date, end_date, output_file)
在没有看到输入文件的情况下,很难准确判断可能出现的问题。立即脱颖而出的一件事是代码的这一部分:
workbook.close()
file_path = "chart testing.xlsx"
output_file = "output.xlsx"
start_date = '2018-01-01'
end_date = '2023-12-31'
generate_seasonal_charts(file_path, start_date, end_date, output_file)
workbook.close() 之后的前四行似乎是您打算在使用参数调用generate_seasonal_charts 之前在主函数中运行的内容。我不能肯定地说,因为我不理解这段代码的上下文,但这似乎是一个缩进错误。
workbook.close()
# main function definition
def main():
file_path = "chart testing.xlsx"
output_file = "output.xlsx"
start_date = '2018-01-01'
end_date = '2023-12-31'
generate_seasonal_charts(file_path, start_date, end_date, output_file)
# main function call
if __name__ == "__main__":
main()