자동화
[파이썬 ] 데이터프레임 엑셀 시트 / 차트 만들기 - pandas / openpyxl 모듈
파이썬 서퍼
2021. 1. 15. 20:35
728x90
from openpyxl import load_workbook
from openpyxl.chart import BarChart, LineChart, RadarChart, AreaChart, Reference
import pandas as pd
data = {'name' : [ 'Jerry', 'Riah', 'Paul'],
'java' : [ 91, 98, 85],
'basic' : [ 81, 63, 83],
'c++' : [ 65, 83, 98],
}
df = pd.DataFrame(data)
df.set_index('name', inplace=True) # name 열을 인덱스로 지정
print(df)
df.to_excel('test_chart.xlsx', sheet_name='Sheet1') # 시트에 데이터 전달
#---------------------------------------------------------------------------
# 차트 작업
wb = load_workbook('test_chart.xlsx')
ws = wb['Sheet1']
data = Reference(ws, min_row=1, max_row=ws.max_row, min_col=2, max_col=ws.max_column)
cats = Reference(ws, min_row=2, max_row=ws.max_row, min_col=1, max_col=1)
chart = BarChart() # 차트 종류 설정 - 세로형 막대
chart.add_data(data, titles_from_data=True) # 차트데이터 : 계열-제목에서 가져옴
chart.set_categories(cats) # 카테고리 설정
ws.add_chart(chart, "F1") # 차트 넣을 위치 지정
wb.save('test_chart.xlsx') # 엑셀파일 저장
https://openpyxl.readthedocs.io/en/stable/charts/introduction.html#chart-types
Charts — openpyxl 3.0.6 documentation
© Copyright 2010 - 2021, See AUTHORS Revision 4e4d4024eb4d.
openpyxl.readthedocs.io
반응형