# '20/01/31更新:右記リンク先更新に伴い、本記事のコードも更新しました→Python csvファイル中にある指定2列を複数ファイルからひとつのExcelファイルを作成する - HK29’s blog
本記事では、下図のような複数のXYデータが列方向へ順番に並んでいるExcelファイルを対象としてます。本プログラムを実行すると、下図のように重ね合わせ散布図を作成する。XYデータの行数が異なっていてもOKである。

■本プログラム
from openpyxl import load_workbook
from openpyxl.chart import ScatterChart,Reference,Series
from openpyxl.chart.text import RichText
from openpyxl.drawing.text import Paragraph, ParagraphProperties, CharacterProperties, Font
def csv2excel_graph(fname):
wb = load_workbook(fname)
rows = wb['Sheet1'].max_row
columns = wb['Sheet1'].max_column
print("rows -> " + str(rows))
print("columns -> " + str(columns))
ws = wb.active
chart = ScatterChart()
myfont = Font(typeface='Calibri')
cp = CharacterProperties(latin=myfont, sz=1400)
chart.title = "hogehoge"
chart.x_axis.title = 'x axis'
chart.x_axis.title.tx.rich.p[0].r[0].rPr = cp
chart.x_axis.txPr = RichText(p=[Paragraph(pPr=ParagraphProperties(defRPr=cp), endParaRPr=cp)])
chart.y_axis.title = 'y axis'
chart.y_axis.title.tx.rich.p[0].r[0].rPr = cp
chart.y_axis.txPr = RichText(p=[Paragraph(pPr=ParagraphProperties(defRPr=cp), endParaRPr=cp)])
for i in range(1, columns, 2):
x_values = Reference(ws, min_col=i, min_row = 2, max_row = rows)
y_values = Reference(ws, min_col=i+1, min_row = 1, max_row = rows)
con = Series(y_values, x_values, title_from_data=True)
con.marker.symbol = 'circle'
con.marker.size = 2
chart.series.append(con)
ws.add_chart(chart, "A18")
wb.save(fname)
if __name__ == '__main__':
inputfile = '200131_x_y.xlsx'
csv2excel_graph(inputfile)
・ちょっと苦労した点
エクセルグラフのフォントサイズの調整をしたくて、下記のようなエラーに出くわした。
AttributeError: 'list' object has no attribute 'rPr'
対策は、p[0].rPr を p[0].r[0].rPr にて解決した。
以上
<広告>
リンク