使用 Python 将多个 matplotlib 图放入 Excel 3
Putting multiple matplotlib graphs into Excel using Python 3
我正在尝试根据我在 Python 3 回调中的数据框创建一些图表并将它们导出到 Excel。我一直在使用以下响应响应中的一些代码,但是当我将它用于多个图表时,它会给我一些奇怪的结果:
Can I insert matplotlib graphs into Excel programmatically?
我的代码是:
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_reults
或 plot_scatter_ts
本身时,它们 运行 并进入 Excel 很好。但是,如果我 运行 它们在一起,只有图 运行 最后出现在 Excel 文档中,所以在这种情况下是散点图。此外,我真的不想看到 Python 界面中的图表,所以如果我摆脱 plot_results
函数中的 plt.show()
散点图由于某种原因变成条形图,这很奇怪,因为这些图都不是条形图,而且它们具有不同的功能。
有人知道我做错了什么吗?
谢谢
18 年 13 月 6 日更新
抱歉有点忙没有机会回到这个。
按照 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:$D502',
'values':'=test!$C:$C502'
})
chart.add_series({
'name':ts2,
'categories': '=test!$D:$D502',
'values':'=test!$E:$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:$E502',
'values':'=test!$C:$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:$D502',
'values':'=test!$C:$C502'
})
chart.add_series({
'name':ts2,
'categories': '=test!$D:$D502',
'values':'=test!$E:$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:$E502',
'values':'=test!$C:$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()
我正在尝试根据我在 Python 3 回调中的数据框创建一些图表并将它们导出到 Excel。我一直在使用以下响应响应中的一些代码,但是当我将它用于多个图表时,它会给我一些奇怪的结果:
Can I insert matplotlib graphs into Excel programmatically?
我的代码是:
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_reults
或 plot_scatter_ts
本身时,它们 运行 并进入 Excel 很好。但是,如果我 运行 它们在一起,只有图 运行 最后出现在 Excel 文档中,所以在这种情况下是散点图。此外,我真的不想看到 Python 界面中的图表,所以如果我摆脱 plot_results
函数中的 plt.show()
散点图由于某种原因变成条形图,这很奇怪,因为这些图都不是条形图,而且它们具有不同的功能。
有人知道我做错了什么吗?
谢谢
18 年 13 月 6 日更新
抱歉有点忙没有机会回到这个。
按照 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:$D502',
'values':'=test!$C:$C502'
})
chart.add_series({
'name':ts2,
'categories': '=test!$D:$D502',
'values':'=test!$E:$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:$E502',
'values':'=test!$C:$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:$D502',
'values':'=test!$C:$C502'
})
chart.add_series({
'name':ts2,
'categories': '=test!$D:$D502',
'values':'=test!$E:$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:$E502',
'values':'=test!$C:$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()