使用Python 3将多个matplotlib图形放入Excel
我正在尝试基于Python 3中调用的数据框架创建一些图形,并将它们导出到Excel中。我一直在使用下面响应中的一些代码,但当我将其用于多个图形时,它会给我一些奇怪的结果: 我的代码是:使用Python 3将多个matplotlib图形放入Excel,python,excel,python-3.x,matplotlib,openpyxl,Python,Excel,Python 3.x,Matplotlib,Openpyxl,我正在尝试基于Python 3中调用的数据框架创建一些图形,并将它们导出到Excel中。我一直在使用下面响应中的一些代码,但当我将其用于多个图形时,它会给我一些奇怪的结果: 我的代码是: import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates import openpyxl filepath = 'C:\Filepath\Template.xlsx' writer = pd.Ex
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import openpyxl
filepath = 'C:\Filepath\Template.xlsx'
writer = pd.ExcelWriter(filepath, engine='xlsxwriter')
back.to_excel(writer, sheet_name='test')
writer.save()
## PLOTS
## ts1 is company 1 and ts2 is company 2
def plot_results(df, ts1, ts2, filepath, cell):
months = mdates.MonthLocator() # every month
fig, ax = plt.subplots()
ax.plot(df['price_date'], df[ts1], label=ts1)
ax.plot(df['price_date'], df[ts2], label=ts2)
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
# ax.set_xlim(datetime.datetime(start_year, start_month_num, start_day_num), datetime.datetime(end_year, end_month_num, end_day_num))
ax.grid(True)
fig.autofmt_xdate()
plt.xlabel('Month/Year')
plt.ylabel('Cumulative Percent Growth')
plt.title('%s and %s Cumulative Percent Growth' % (ts1, ts2))
plt.legend()
plt.savefig('plot.png', dpi=150)
plt.show()
wb = openpyxl.load_workbook(filepath)
ws = wb.active
img = openpyxl.drawing.image.Image('plot.png')
img.anchor(ws.cell(cell))
ws.add_image(img)
wb.save(filepath)
def plot_scatter_ts(df, ts1, ts2, filepath, cell):
plt.xlabel('%s Price ($)' % ts1)
plt.ylabel('%s Price ($)' % ts2)
plt.title('%s and %s Price Scatterplot' % (ts1, ts2))
plt.scatter(df[ts1], df[ts2])
plt.show()
wb = openpyxl.load_workbook(filepath)
ws = wb.active
plt.savefig('plot.png', dpi=150)
img = openpyxl.drawing.image.Image('plot.png')
img.anchor(ws.cell(cell))
ws.add_image(img)
wb.save(filepath)
plot_results(back, 'adj_close_price4.0', 'adj_close_price26.0', filepath, 'P2')
plot_scatter_ts(back, 'adj_close_price4.0', 'adj_close_price26.0', filepath, 'P34')
当我单独运行函数plot\u reults或plot\u scatters时,它们会运行并进入Excel。但是如果我把它们一起运行,只有最后运行的图形会出现在Excel文档中,所以在本例中是散点图。此外,我真的不想在Python界面中看到图形,因此如果我在plot_results函数中去掉plt.show,散点图出于某种原因会变成条形图,这很奇怪,因为这些图形都不是条形图,它们在不同的函数中
有人知道我做错了什么吗
谢谢
更新13/6/18
抱歉,有点忙,我没机会再谈这个了
正如Screenpaver建议的那样,我已经使用Pandas xlsxwriter重写了我的代码。但是,当我试图做一个以上的情节,它似乎仍然混淆了情节。我的代码如下:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import openpyxl
filepath = 'C:\...\Template.xlsx'
## Chart 1
def plot_results(df, ts1, ts2, sheet_name, filepath, cell):
## Create Pandas Excel writer using Xlswriter as the engine
writer = pd.ExcelWriter(filepath, engine='xlsxwriter')
back.to_excel(writer, sheet_name=sheet_name, startrow=1, startcol=1)
## Access the Xlswriter workbook and worksheets objects from the dataframe.
workbook = writer.book
worksheet = writer.sheets[sheet_name]
## Create a chart object
chart = workbook.add_chart({'type':'line'})
## Calculate extremes for axes
min_x1 = back[ts1].min()
max_x1 = back[ts1].max()
min_x2 = back[ts2].min()
max_x2 = back[ts2].max()
min_x = min(min_x1, min_x2)
max_x = max(max_x1, max_x2)
## Configure the series of the chart from the dataframe data
chart.add_series({
'name':ts1,
'categories': '=test!$D$3:$D502',
'values':'=test!$C$3:$C502'
})
chart.add_series({
'name':ts2,
'categories': '=test!$D$3:$D502',
'values':'=test!$E$3:$E502'
})
## Configure chart axis
chart.set_x_axis({'name':'Month/Year',
'date_axis':True,
'num_format': 'mm/yy',
'major_gridlines':{
'visible':True,
'line':{'width':1, 'dash_type':'dash'}
}})
chart.set_y_axis({'name':'Cumulative Percent Growth',
'min':min_x,
'max':max_x,
'major_gridlines':{
'visible':True,
'line':{'width':1, 'dash_type':'dash'}
}
})
chart.set_title({'name':'%s and %s Cumulative Percent Growth' % (ts1, ts2)})
chart.set_legend({'position':'bottom'})
chart.set_chartarea({'border':{'none':True}})
## Insert chart into worksheet
worksheet.insert_chart(cell, chart)
writer.save()
## Chart 2
def plot_scatter_ts(df, ts1, ts2, sheet_name, filepath, cell):
## Create Pandas Excel writer using Xlswriter as the engine
writer = pd.ExcelWriter(filepath, engine='xlsxwriter')
back.to_excel(writer, sheet_name=sheet_name, startrow=1, startcol=1)
## Access the Xlswriter workbook and worksheets objects from the dataframe.
workbook = writer.book
worksheet = writer.sheets[sheet_name]
## Create a chart object
chart = workbook.add_chart({'type':'scatter'})
min_x1 = back[ts1].min()
max_x1 = back[ts1].max()
min_x2 = back[ts2].min()
max_x2 = back[ts2].max()
## Configure the series of the chart from the dataframe data
chart.add_series({
# 'name':'Series1',
'categories': 'test!$E$3:$E502',
'values':'=test!$C$3:$C502'
})
## Configure chart axis
chart.set_x_axis({'name':ts1,
'min':min_x2,
'max':max_x2})
chart.set_y_axis({'name':ts2,
'min':min_x1,
'max':max_x1})
chart.set_title({'name':'%s and %s Price Scatterplot' % (ts1, ts2)})
chart.set_legend({'none':True})
chart.set_chartarea({'border':{'none':True}})
## Insert chart into worksheet
worksheet.insert_chart(cell, chart)
writer.save()
plot_scatter_ts(back, 'adj_close_price4.0', 'adj_close_price26.0', 'test2', filepath, 'Q18')
plot_results(back, 'series1', 'series2', 'test2', filepath, 'Q2')
当分别运行另一个函数时,每个函数都很好,但当我运行这两个函数时,会得到一个混乱的图
感谢感谢screenpaver通过将write移出以下功能使其正常工作:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import openpyxl
filepath = 'C:\...\Template.xlsx'
sheet_name='test'
writer = pd.ExcelWriter(filepath, engine='xlsxwriter')
## Chart 1
def plot_results(writer, df, ts1, ts2, sheet_name, filepath, cell):
## Create Pandas Excel writer using Xlswriter as the engine
df.to_excel(writer, sheet_name=sheet_name, startrow=1, startcol=1)
## Access the Xlswriter workbook and worksheets objects from the dataframe.
workbook = writer.book
worksheet = writer.sheets[sheet_name]
## Create a chart object
chart = workbook.add_chart({'type':'line'})
## Calculate extremes for axes
min_x1 = df[ts1].min()
max_x1 = df[ts1].max()
min_x2 = df[ts2].min()
max_x2 = df[ts2].max()
min_x = min(min_x1, min_x2)
max_x = max(max_x1, max_x2)
## Configure the series of the chart from the dataframe data
chart.add_series({
'name':ts1,
'categories': '=test!$D$3:$D502',
'values':'=test!$C$3:$C502'
})
chart.add_series({
'name':ts2,
'categories': '=test!$D$3:$D502',
'values':'=test!$E$3:$E502'
})
## Configure chart axis
chart.set_x_axis({'name':'Month/Year',
'date_axis':True,
'num_format': 'mm/yy',
'major_gridlines':{
'visible':True,
'line':{'width':1, 'dash_type':'dash'}
}})
chart.set_y_axis({'name':'Cumulative Percent Growth',
'min':min_x,
'max':max_x,
'major_gridlines':{
'visible':True,
'line':{'width':1, 'dash_type':'dash'}
}
})
chart.set_title({'name':'%s and %s Cumulative Percent Growth' % (ts1, ts2)})
chart.set_legend({'position':'bottom'})
chart.set_chartarea({'border':{'none':True}})
## Insert chart into worksheet
worksheet.insert_chart(cell, chart)
## Chart 2
def plot_scatter_ts(writer, df, ts1, ts2, sheet_name, filepath, cell):
## Create Pandas Excel writer using Xlswriter as the engine
df.to_excel(writer, sheet_name=sheet_name, startrow=1, startcol=1)
## Access the Xlswriter workbook and worksheets objects from the dataframe.
workbook = writer.book
worksheet = writer.sheets[sheet_name]
## Create a chart object
chart = workbook.add_chart({'type':'scatter'})
min_x1 = df[ts1].min()
max_x1 = df[ts1].max()
min_x2 = df[ts2].min()
max_x2 = df[ts2].max()
## Configure the series of the chart from the dataframe data
chart.add_series({
# 'name':'Series1',
'categories': 'test!$E$3:$E502',
'values':'=test!$C$3:$C502'
})
## Configure chart axis
chart.set_x_axis({'name':ts1,
'min':min_x2,
'max':max_x2})
chart.set_y_axis({'name':ts2,
'min':min_x1,
'max':max_x1})
chart.set_title({'name':'%s and %s Price Scatterplot' % (ts1, ts2)})
chart.set_legend({'none':True})
chart.set_chartarea({'border':{'none':True}})
## Insert chart into worksheet
worksheet.insert_chart(cell, chart)
plot_scatter_ts(writer, back, 'series1', 'series2', sheet_name, filepath, 'Q18')
plot_results(writer, back, 'series1', 'series2', sheet_name, filepath, 'Q2')
writer.save()
你看过Pandas xlsxwriter接口图表的使用情况吗?add_系列等等?感谢screenpaver,我在上面添加了一个使用xlswriter的更新,但是在运行这两个函数时,图形仍然混乱。第二个函数不是覆盖了第一个函数创建的电子表格吗?似乎您希望在函数之外创建并传递“writer”,然后在第二个函数调用返回后使用writer.save。感谢screenpaver让它工作起来!