Quiero exportar varios gráficos que he creado usando xlsxwriter en varias hojas en un solo excel. Tengo dos marcos de datos como abajo:
df_a = pd.DataFrame({'User':['101','102','103','104','105','106'],'CountA':[7,8,9,10,11,12],'CountB':[1,2,3,4,5,6],'CountC':[13,14,15,16,17,18]})
df_b = pd.DataFrame({'User':['107','108','109','110','111','112'],'ValA':[10,20,30,40,50,60],'ValB':[70,80,90,100,110,120],'ValC':[130,140,150,160,170,180]})
He creado con éxito un archivo de Excel, a saber, "test.xlsx" que contiene df_a y su correspondiente gráfico de barras apiladas utilizando el código siguiente:
#Create a Pandas Excel writer using XlsxWriter as the engine.
excel_file_a = 'test.xlsx'
sheet_name_a = 'testA'
writer = pd.ExcelWriter(excel_file_a, engine='xlsxwriter')
df_a.to_excel(writer, sheet_name=sheet_name_a,index=False)
#Access the XlsxWriter workbook and worksheet objects from the dataframe.
workbook = writer.book
worksheet_a = writer.sheets[sheet_name_a]
#Create a chart object.
chart_a = workbook.add_chart({'type': 'column', 'subtype': 'stacked'})
#Configure the series of the chart from the dataframe data.
for col_num in range(1, 4):
chart_a.add_series({
'name': ['testA', 0, col_num],
'categories': ['testA', 1, 0, 5, 0],
'values': ['testA', 1, col_num, 5, col_num],
'gap': 2,
})
#Insert the chart into the worksheet.
worksheet_a.insert_chart('G2', chart_a)
#Close the Pandas Excel writer and output the Excel file.
writer.save()
Sin embargo, también quiero df_b y su respectivo gráfico de barras apiladas en el mismo archivo de Excel, "test.xlsx" pero en una hoja diferente, digamos nombre de hoja .
2 respuestas
Este es un buen lugar para usar un bucle. Por ejemplo:
# You only need one of each of these
excel_file = 'test.xlsx'
writer = pd.ExcelWriter(excel_file_a, engine='xlsxwriter')
workbook = writer.book
dataframes = (df_a, df_b)
# Loop through our list of dataframes
for i in range(len(dataframes)):
sheet_name = 'test' + 'abcdefghijklmnop'[i] # testa, testb, etc.
dataframe = dataframes[i]
dataframe.to_excel(writer, sheet_name=sheet_name, index=False)
worksheet = writer.sheets[sheet_name]
....
# all of the other stuff down as far as...
worksheet.insert_chart('G2', chart)
# Now that we have finished our loop
writer.save()
Acabo de copiar y pegar tu código y he cambiado un par de cosas. No sé cuál fue tu problema, tal vez estabas sobrescribiendo algo.
excel_file_a = 'test.xlsx'
sheet_name_a = 'testA'
sheet_name_b = 'testB'
writer = pd.ExcelWriter(excel_file_a, engine='xlsxwriter')
df_a.to_excel(writer, sheet_name=sheet_name_a,index=False)
df_b.to_excel(writer, sheet_name=sheet_name_b,index=False)
workbook = writer.book
worksheet_a = writer.sheets[sheet_name_a]
worksheet_b = writer.sheets[sheet_name_b]
chart_a= workbook.add_chart({'type': 'column', 'subtype': 'stacked'})
chart_b= workbook.add_chart({'type': 'column', 'subtype': 'stacked'})
for col_num in range(1, 4):
chart_a.add_series({
'name': ['testA', 0, col_num],
'categories': ['testA', 1, 0, 5, 0],
'values': ['testA', 1, col_num, 5, col_num],
'gap': 2,
})
for col_num in range(1, 4):
chart_b.add_series({
'name': ['testB', 0, col_num],
'categories': ['testB', 1, 0, 5, 0],
'values': ['testB', 1, col_num, 5, col_num],
'gap': 2,
})
worksheet_a.insert_chart('G2', chart_a)
worksheet_b.insert_chart('G3', chart_b)
writer.save()
Preguntas relacionadas
Nuevas preguntas
python
Python es un lenguaje de programación multipropósito, de tipificación dinámica y de múltiples paradigmas. Está diseñado para ser rápido de aprender, comprender y usar, y hacer cumplir una sintaxis limpia y uniforme. Tenga en cuenta que Python 2 está oficialmente fuera de soporte a partir del 01-01-2020. Aún así, para preguntas de Python específicas de la versión, agregue la etiqueta [python-2.7] o [python-3.x]. Cuando utilice una variante de Python (por ejemplo, Jython, PyPy) o una biblioteca (por ejemplo, Pandas y NumPy), inclúyala en las etiquetas.